ssh操作服务器
# -*- coding: utf-8 -*- """ Created on Wed Mar 20 10:15:16 2019 @author: Kuma 1、 ssh连接服务器 2、 scp获取安装脚本及安装包 1)sftp传输 3、 执行安装脚本 """ import paramiko #pip3 install paramiko import logging class sshOperate(): def __init__(self): #创建SSHClient对象 self.ssh = paramiko.SSHClient() def sshLogin(self, ip, username, password): try: #允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面 self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 建立连接 self.ssh.connect(ip,port,user,password,timeout = 10) except paramiko.AuthenticationException: logging.warning("username or password error") return 1001 except paramiko.ssh_exception.NoValidConnectionsError: logging.warning("connect time out") return 1002 except: logging.warning('unknow error') print("Unexpected error:", sys.exc_info()[0]) return 1003 return 1000 def executeCommand(self,command): #执行命令,输出结果在stdout中,如果是错误则放在stderr中 stdin, stdout, stderr = self.ssh.exec_command(command) print(stdout.read().decode()) def sftp(self, ip, user, passwd): transport = paramiko.Transport((ip, 22)) transport.connect(username=user, password=passwd) sftp = paramiko.SFTPClient.from_transport(transport)#如果连接需要密钥,则要加上一个参数,hostkey="密钥" sftp.put('clear_reload_1.5.sh', '/home/user/clear_reload_1.5.sh') #sftp.put('jcf-platform-1.5.2-20190315-RUN.tar.gz', '/home/user/exefile') #大文件传的太慢了 transport.close()#关闭连接 def sshLogout(self): #logging.warning('logout') #断开连接 self.ssh.close() if __name__ == '__main__': # 服务器相关信息,下面输入你个人的用户名、密码、ip等信息 #ip = "10.xxx.xx.xxx" #port = 22 user = "user" #password = "passwd" shFile = "shFile" exeFile = "exeFile" ipDict = { "10.xxx.xxx.xxx" :"passwd" } mySsh = sshOperate() for ip, password in ipDict.items(): mySsh.sshLogin(ip, user, password) mySsh.sftp(ip, user, password) mySsh.executeCommand("chmod 777 " + shFile) #mySsh.executeCommand("./" + shFile + " " + exeFile) mySsh.sshLogout()