python ssh远程执行shell命令Python实现SSH远程登陆,并执行命令的方法
一,推荐paramiko,可实现命令交互,在登录无密码设备时需要加上异常处理,如下:
paramiko可能出现连接失败,大概率是因为本地和设备的加密算法不一致导致
import paramiko class mySSH: def __init__(self, host='', username='liauto', port=22, password=''): self.ip = host self.port = port self.username = username self.password = password self.connection = None def connect(self): self.connection = paramiko.SSHClient() self.connection.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: if self.password != '': self.connection.connect(self.ip, self.port, self.username, (str(self.password)), timeout=5.0) else: try: self.connection.connect(self.ip, self.port, self.username, look_for_keys=False, allow_agent=False, timeout=5.0) except paramiko.ssh_exception.SSHException: self.connection.get_transport().auth_none(self.username) self.connection.exec_command('uname -a') self.connection.sftp = paramiko.SFTPClient.from_transport(self.connection.get_transport()) except Exception as e: try: print(str(e.args)) self.connection = None finally: e = None del e if __name__ == '__main__': test = mySSH() test.connect() # 执行命令并获取命令结果 stdin, stdout, stderr = test.connection.exec_command('uname -a') # stdin为输入的命令 # stdout为命令返回的结果 # stderr为命令错误时返回的结果 print(stdout.read())
paramiko示例使用:
PYTHON PARAMIKO
Python paramiko.ECDSAKey方法代码示例
python自动化第三方库之paramiko库:连接远程服务器并通过ssh协议远程执行命令
二、推荐subprocess.Popen
可以将远程命令结果返回,可以做命令超时处理,再执行一些返回时间较长的命令时,可以选择
proc1 = subprocess.Popen(f'ssh -o "StrictHostKeyChecking no" liauto@{soc_ip} "{update_mcu}"', shell=True, stderr=subprocess.PIPE, stdin=subprocess.PIPE, stdout=subprocess.PIPE) try: outs, errs = proc1.communicate(timeout=10 * 60, input=None) except subprocess.TimeoutExpired: self.logger.info('【{}】解压并升级MCU时超时,用时10min,任务终止'.format(self.orin_type)) self.logger.error('【{}】errs:{}'.format(self.orin_type, errs.decode('UTF-8'))) proc1.kill()
三、os.popen 对于一些很快执行结束的命令是不错的选择
cmd = "ls -al /"
r = os.popen(f'ssh -o "StrictHostKeyChecking no" liauto@{host} "{cmd}"') data = r.readlines() print(data)
四、os.system执行完命令不返回结果,不推荐使用
cmd = “ls -al /”
os.system(f’ssh -o “StrictHostKeyChecking no” liauto@{host} “{cmd}”‘)