paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。
实例1:
多线程批量执行命令:
#-*- coding:utf-8 -*- #!/usr/bin/python import paramiko import threading def ssh2(ip,username,passwd,cmd): try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,22,username,passwd,timeout=5) for m in cmd: stdin,stdout,stderr = ssh.exec_command(m) out = stdout.readlines() for o in out: print o, print '%s\tOK\n' % (ip) ssh.close() except: print '%s\tError\n' % (ip) if __name__=='__main__': cmd = ['cal','echo hello!'] username = "root" passwd = "123456" threads = [] print "Begin......" for i in range(1,254): ip = '192.168.1.'+str(i) a=threading.Thread(target=ssh2,args=(ip,username,passwd,cmd)) a.start()
实例2,上传本地文件到服务器:
#!/usr/bin/python import paramiko t = paramiko.Transport(("192.168.1.60",22)) t.connect(username = "root",password = "123456") sftp = paramiko.SFTPClient.from_transport(t) remotepath='/tmp/system.log' localpath='/tmp/boot.log' sftp.put(localpath,remotepath) t.close()
实例3,把服务器文件下载到本地
#!/usr/bin/python import paramiko t = paramiko.Transport(('192.168.1.60',22)) t.connect(username = 'root', password = '123456') sftp = paramiko.SFTPClient.from_transport(t) remotepath='/var/log/boot.log' localpath='/tmp/boot.log' sftp.get(remotepath, localpath) t.close()