python 下的paramiko功能很之强大。我们所熟悉的Ansible就是用paramiko编写。paramiko主要是通过ssh协议对远程主机的管理。比如:执行远程主机的CLI、上传和下载文件等。
1.通过使用paramiko 远程管理主机
#!/usr/bin/env python#-*- coding:utf-8 -*-#Author;David.Zhang#Function:Remote management server using paramikoimport paramikodef parserHost(): HOSTS=['192.168.1.1', '192.168.1.2', '192.168.1.3'] PORT=22 USERNAME='root' PASSWD='xxxxxx' ld=[] for HOST in HOSTS: try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=HOST, username=USERNAME, password=PASSWD, port=PORT) stdin, stdout, stderr = ssh.exec_command('rpm -qa | grep nginx | md5sum') ssh.close() except: ld.append(HOST) return ldif __name__ == "__main__": print parserHost()#HOSTS 要处理的服务器列表#ld 当某台服务器处理异常,ld作为buffer存放处理异常的服务器,方便排查错误。2. 通过使用paramiko 上传和下载文件
#!/usr/bin/env python#-*- coding:utf-8 -*-#Author:David.Zhangimport paramikodef sftp(): HOSTS=['192.168.1.1', '192.168.1.2'] PORT=22 USERNAME='root' PASSWD='xxxxx' ld=[] for HOST in HOSTS: try: ssh = paramiko.Transport((HOST,PORT)) ssh.connect(username=USERNAME, password=PASSWD) sftp = paramiko.SFTPClient.from_transport(ssh) remotepath = '/root/file1' localpath = '/root/file1' sftp.put(localpath, remotepath) #上传 sftp.get(remotpath, localpath) #下载 sftp.close() except: ld.append(HOST)if __name__ == "__main__": print sftp()