Python | paramiko模块
一、简介
paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。
由于使用的是python这样的能够跨平台运行的语言,所以所有python支持的平台,如Linux, Solaris, BSD, MacOS X, Windows等,paramiko都可以支持,因此,如果需要使用SSH从一个平台连接到另外一个平台,进行一系列的操作时,paramiko是最佳工具之一
二、安装
安装pycrypto跟paramiko
pip install pycryptopip install paramiko
三、例子
1、ssh登录
#!/usr/bin/python# -*- coding: utf-8 -*-# Filename: paramiko_ssh.pyimport paramikohost = '10.2.68.36'port = 36000username = 'root'password = 'xxxxxx'if __name__ == "__main__": client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: client.connect(host, port, username, password, look_for_keys=False) print "Connect to %s %d succeed" %(host, port) except Exception, e: print e client.close()
输出结果:
Connect to 10.2.68.36 36000 succeed
2、执行命令
#!/usr/bin/python# -*- coding: utf-8 -*-# Filename: paramiko_exec.pyimport paramikohost = '10.2.68.36'port = 36000username = 'root'password = 'xxxxxx'if __name__ == "__main__": client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: client.connect(host, port, username, password, look_for_keys=False) stdin, stdout, stderr = client.exec_command('date') print host, stdout.read(), except Exception, e: print e client.close()
输出结果:
10.2.68.36 Wed Sep 4 21:48:38 CST 2013
3、使用配置文件批量登陆操作
#!/usr/bin/env python# -*- coding: utf-8 -*-# Filename: paramiko_config.pyimport paramikoimport osfrom ConfigParser import ConfigParserconfig_file = 'config.ini'config = ConfigParser()config.read(config_file)host = ''.join(config.get('IP', 'ipaddress'))address = host.split(';')username = 'root'password = 'xxoo@TENCENT888'port = 36000if __name__ == '__main__': for ip in address: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: client.connect(ip, port, username, password, look_for_keys=False) print ip stdin, stdout, stderr = client.exec_command('date') print stdout.read(), except Exception, e: print e client.close()
config.ini配置文件
[IP]ipaddress = 10.2.68.36;10.2.68.38
输出结果:
10.2.68.36Thu Sep 5 17:25:20 CST 201310.2.68.38Thu Sep 5 17:16:54 CST 2013
4、文件传输
#!/usr/bin/python# -*- coding: utf-8 -*-# Filename: paramiko_exec.pyimport osimport paramikoimport datetimefrom scp import SCPClienthost = '10.2.68.36'port = 36000username = 'root'password = 'xxxxxx'local_path = '/tmp/'remote_path = '/root/tmp'if __name__ == "__main__": client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: client.connect(host, port, username, password, look_for_keys=False) scp = SCPClient(client.get_transport()) if os.path.isfile(local_path): scp.put(local_path, remote_path) else: scp.put(local_path, remote_path, recursive=True) except Exception, e: print e client.close()
备注
因为paramiko本身是不支持目录传输的,因此找了scp.py 模块代替paramiko的sftp只需要添加recursive=True参数即可,其实原理也就是调用os.walk
5、功能整合
#!/usr/bin/env python# -*- coding: utf-8 -*-# Filename: pssh.pyimport osimport datetimeimport paramikofrom scp import SCPClientfrom ConfigParser import ConfigParserconfig_file = 'config.ini'config = ConfigParser()config.read(config_file)host = ''.join(config.get('IP', 'ipaddress'))address = host.split(';')class pssh(): def __init__(self, hostname, port, username, password, look_for_keys=False): self.hostname = hostname self.port = port self.username = username self.password = password self.look_for_keys = look_for_keys self.client = None self.connect() def connect(self): if self.client is None: self.client = paramiko.SSHClient() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self.client.connect(self.hostname, self.port, self.username, self.password, look_for_keys=self.look_for_keys) except Exception, e: print e def command(self, cmd): self.connect() stdin, stdout, stderr = self.client.exec_command(cmd) message = stdout.read() error = stderr.read() if len(error) > 0: result = False msg = error else: result = True msg = message return result, msg def upload(self, local_path, remote_path): self.connect() scp = SCPClient(self.client.get_transport()) try: if os.path.isfile(local_path): scp.put(local_path, remote_path) else: scp.put(local_path, remote_path, recursive=True) except Exception, e: print e def download(self, remote_path): self.connect() scp = SCPClient(self.client.get_transport()) try: if os.path.isfile(remote_path): scp.get(remote_path) else: scp.get(remote_path, recursive=True) except Exception, e: print e def close(self): self.client.close()def main(): client = pssh('10.2.68.36', 36000, 'root', 'xxoo@TENCENT888') client.download('/root/heartbeat3')if __name__ == "__main__": main()
好了,paramiko模块介绍到这里,本来还想弄个多线程的,剩下的自己自由发挥吧!