paramiko 远程运行以及上传文件(批量运维)

来源:互联网 发布:阿金淘宝店 编辑:程序博客网 时间:2024/06/11 16:07
#!/usr/bin/env python
#coding = utf-8




'''
version : 2015-01-21
author : vdon
contact : qfang.inc


password.csv fied format:
    ipaddress,username,password
'''
import csv,os,sys
import paramiko


class SshRemote(object):
    def __init__(self,ipaddress,username,password,port=22):
        self.__ipaddress = ipaddress
        self.__username = username
        self.__password = password
        self.__port = port
        
    def execCommand(self,command):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(self.__ipaddress,self.__port,self.__username,self.__password)
        stdin,stdout,stderr = ssh.exec_command(command)
        log_file = open('remoteDeploy.log','ab+')
        sys.stdout = log_file
        print "\n--- --- Remote machine %s log --- --- \n" % self.__ipaddress
        print stdout.readlines()
        log_file.close()
        ssh.close()
        
    def sftpSend(self,local_path,remote_path):
        trans = paramiko.Transport((self.__ipaddress,self.__port))
        trans.connect(username = self.__username,password = self.__password)
        sftp = paramiko.SFTPClient.from_transport(trans)
        sftp.put(local_path,remote_path)
        trans.close()
        
        
        
def main():
    path_password = "password.csv"
    if not os.path.isfile(path_password):
        print "Can't find --password.csv-- under path : %s" % os.getcwd()
        exit()
        
    reader = csv.reader(open(path_password,'rb'))
    for line in reader:
        if reader.line_num == 1:
            continue
        
        ipaddress = line[0]
        username = line[1]
        password = line[2]
        remote = SshRemote(ipaddress,username,password)
        
        local_path = "/opt/script/safeInit.py"
        remote_path = "/tmp/safeInit.py"
        remote.sftpSend(local_path,remote_path)
        
        remote.execCommand('/usr/bin/python /tmp/safeInit.py')
        
        remote.execCommand('/bin/mkdir -pv /opt/script')
        
        local_path = "/opt/script/iptables.sh"
        remote_path = "/opt/script/iptables.sh"
        remote.sftpSend(local_path,remote_path)
        
    
if __name__ == '__main__':
    main()
    
        
    

0 0
原创粉丝点击