python ssh接続実行命令を実現する2つの方式Demo

2393 ワード

pythonバージョン:python 3.7.4
Demo:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################
#author: SkyJ
#date  : 2019/7/17
################################################

import os
import sys
import string
import datetime
import time
import paramiko   #  paramiko

hostname = "192.168.1.11"
username = "root"
password = "SkyJ"
cmdList = ['ls -l
', 'df -h
'] # ssh def sshRunCmd(hostname, username, password, cmdList): try: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # ssh client.connect(hostname=hostname, port=22, username=username, password=password) # ssh ssh = client.get_transport().open_session() ssh.get_pty() ssh.invoke_shell() # for cmd in cmdList: ssh.sendall(cmd) time.sleep(0.5) result = ssh.recv(102400) result = result.decode(encoding='UTF-8',errors='strict') print (result) except Exception as e: print ("[%s] %s target failed, the reason is %s" % (datetime.datetime.now(), hostname, str(e))) else: print ("[%s] %s target success" % (datetime.datetime.now(), hostname)) finally: ssh.close() client.close() # ssh def sshRunCmd2(hostname, username, password, cmdList): try: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # ssh client.connect(hostname=hostname, port=22, username=username, password=password) # for cmd in cmdList: stdin, stdout, stderr = client.exec_command(cmd) result = stdout.read() result = result.decode(encoding='UTF-8',errors='strict') print (result) except Exception as e: print ("[%s] %s target failed, the reason is %s" % (datetime.datetime.now(), hostname, str(e))) else: print ("[%s] %s target success" % (datetime.datetime.now(), hostname)) finally: client.close() if __name__ == '__main__': sshRunCmd(hostname, username, password, cmdList) sshRunCmd2(hostname, username, password, cmdList)