SSH 为 Secure Shell 的缩写,由 IETF 的网络小组(Network Working Group)所制定;SSH 为创建在应用层基础上的安全协议。SSH 是目前较可靠,专为远程登陆会话和其余网络服务提供安全性的协议。利用 SSH 协议能够有效防止远程管理过程当中的信息泄露问题.python
paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的链接。paramiko支持Linux, Solaris, BSD, MacOS X, Windows等平台经过SSH从一个平台链接到另一个平台。利用该模块,能够方便的进行ssh链接和sftp协议进行sftp文件传输。mysql
#基于ssh,用于链接远程服务器作操做:远程执行命令,上传或下载文件 import paramiko #建立一个ssh对象 client = paramiko.SSHClient() #2.解决问题:首次链接,会出现 # Are you sure you want to continue connecting (yes/no)? yes # 自动选择yes # 容许链接不在know_hosts文件中的主机 client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #3.链接服务器 client.connect(hostname='172.25.254.19',port=22,username='root',password='westos') #4.执行操做 stdin,stdout,stderr = client.exec_command('hostname')#标准输入,标准输出,标准错误输出。 #Execute a command on the SSH server. A new `.Channel` is opened and # the requested command is executed. The command's input and output # streams are returned as Python ``file``-like objects representing # stdin, stdout, and stderr. #5.获取命令的执行结果 res = stdout.read().decode('utf-8')#使结果具备可读性 print(res) #6.断开链接 client.close()
批量链接host.txt文件中的主机,返回执行结果
格式:172.25.254.1:22:root:westosios
import paramiko with open('host.txt') as f: #保证host.txt文件在当前目录下 hostinfos = f.readlines() #列表形式,['172.25.254.1:22:root:westos\n', '172.25.254.2:22:root:westos\n', '172.25.254.3:22:root:westos\n', '172.25.254.19:22:root:westos\n'] for hostinfo in hostinfos: hostinfo = hostinfo.strip() #去掉空格,字符串格式,172.25.254.2:22:root:westos print('正在链接%s主机' %(hostinfo.split(':')[0])) hostname,port,username,passwd = hostinfo.split(':') try: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=hostname,port=port,username=username,password=passwd) stdin,stdout,stderr = client.exec_command('hostname') res = stdout.read().decode('utf-8') print('结果为:',res) except Exception as e : print("Connection is failed,the reason is :",e) finally: client.close() print("链接结束")
免密登陆远程主机
首先在须要链接的主机上生成一对公钥和私钥,本机获取到须要链接的主机的私钥时,就能够经过公私钥配对,登录远程主机。
这里须要id_rsa存放你所链接的主机的私钥web
import paramiko from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException def conn(cmd,hostname,port=22,username='root'): client = paramiko.SSHClient() private_key = paramiko.RSAKey.from_private_key_file('id_rsa')#id_rsa存放私钥 client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: client.connect(hostname=hostname, port=port,username=username,pkey=private_key) except NoValidConnectionsError as e: print('...链接失败...') except AuthenticationException as e: print('...密码错误...') else: stdin, stdout, stderr = client.exec_command(cmd) result = stdout.read().decode('utf-8') print(result) finally: client.close() if __name__=='__main__': for count in range(13,20): hostname = '172.25.254.%s' %(count) print('正在链接主机:',hostname) conn('hostname',hostname) print("...链接结束...")
sftp是Secure File Transfer Protocol的缩写,安全文件传送协议。能够为传输文件提供一种安全的网络的加密方法。sql
import paramiko tran = paramiko.Transport('172.25.254.19',22) tran.connect(username='root',password='westos') sftp = paramiko.SFTPClient.from_transport(tran) #class SFTPClient(BaseSFTP, ClosingContextManager) #SFTP client object. # Used to open an SFTP session across an open SSH `.Transport` and perform # remote file operations. # Instances of this class may be used as context managers. sftp.put('/home/kiosk/PycharmProjects/day18/07_pratice.py','/mnt/practice.py') sftp.get('/mnt/passwd','hallo') tran.close()
使paramiko模块执行本身想要的操做shell
import paramiko import os from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException, SSHException class SshRrmote(object): def __init__(self,cmd,hostname,port,username,passwd): self.hostname = hostname self.passwd = passwd self.cmd = cmd self.username = username self.port = port def run(self): """默认调用的内容""" # cmd hostname # put local_file remote_file # get remote_file local_file cmd_str = self.cmd.split()[0] # cmd # 类的反射, 判断类里面是否能够支持该操做? if hasattr(self, 'do_' + cmd_str): # do_cmd getattr(self, 'do_' + cmd_str)() else: print("目前不支持该功能") def do_cmd(self): client = paramiko.SSHClient() try: client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=self.hostname,port=int(self.port),username=self.username,password=self.passwd) except NoValidConnectionsError as e: print('...链接失败...') except AuthenticationException as e: print('...密码错误...') else: cmd = ' '.join(self.cmd.split()[1:]) stdin, stdout, stderr = client.exec_command(cmd) result = stdout.read().decode('utf-8') print('执行结果',result) finally: print('断开%s的链接' %(self.hostname)) client.close() def do_get(self): #有待改进,由于链接多个主机时,会覆盖文件 print('开始下载') try: trans = paramiko.Transport(self.hostname,int(self.port)) trans.connect(username=self.username,password=self.passwd) print('hello') except SSHException as e: print("链接失败") else: sftp = paramiko.SFTPClient.from_transport(trans) cmd = self.cmd.split()[1:] if len(cmd)==2: sftp.get(cmd[0],cmd[1]) print("下载文件%s成功,并保存为%s" %(cmd[0],cmd[1])) else: print("参数有误") trans.close() def do_put(self): # put /tmp/passwd /tmp/passwd # 将本机的/tmp/passwd文件上传到远程主机的/tmp/passwd; print("开始上传") #注意你使用的用户是否为kiosk try: trans = paramiko.Transport(self.hostname, int(self.port)) trans.connect(username=self.username, password=self.passwd) except SSHException as e: print("链接失败") else: sftp = paramiko.SFTPClient.from_transport(trans) cmd = self.cmd.split()[1:] if len(cmd) == 2: sftp.put(cmd[0],cmd[1]) print("上传文件%s成功,并保存为%s" %(cmd[0], cmd[1])) else: print("参数有误") trans.close() #1.选择要操做的主机组:mysql,web,ftp # 主机信息怎么存?将不一样的主机信息存放在不一样的文件中 #2.根据选择的主机组,显示包含的主机IP/主机名 #3.让用户确认信息,选择须要批量执行的命令 # -cmd shell命令 # -put 本地文件 远程文件 # -get 远程文件 本地文件 def main(): groups = [file.rstrip('.conf') for file in os.listdir('conf')] print('主机组显示'.center(50,'*')) [print('\t',item) for item in groups] choiceGroup = input("请选择批量操做的主机组(eg:web):") with open('conf/'+choiceGroup+'.conf') as f: info = f.readlines() print("批量执行脚本".center(50, '*')) while True: cmd = input(">>").strip() if cmd: if cmd =='exit': print("链接执行结束") break for item in info: item=item.strip() print(item.split(':')[0].center(50,'-')) hostname,port,username,passwd = item.split(':') ssh = SshRrmote(cmd,hostname,port,username,passwd) ssh.run() main()