使用Python实现ssh client功能
依赖模块:paramiko
安装方式:pip3 install paramiko
或者 sudo apt-get install python-paramiko
具体实现的代码:
#导入paramiko模块
import paramiko
#导入ssh client模块
from paramiko.client import SSHClient, AutoAddPolicy
#导入异常处理
from paramiko import AuthenticationException
from paramiko.ssh_exception import NoValidConnectionsError
#创建SshClient 类
class SshClient():
#初始化
def __init__(self):
self.ssh_client = SSHClient()
#登录
def ssh_login(self, host_ip, username, password):
try:
#允许连接不在known_hosts文件中的主机,及自动输入yes
self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
self.ssh_client.connect(host_ip, port=22, username=username, password=password)
except AuthenticationException:
logging.warning('username or password error')
return 1001
except NovalidConnectionsError:
logging.warning('connect time out')
return 1002
except:
print("Unexpected error:", sys.exc_info()[0])
return 1003
return 1000
def execute_some_command(self, command):
#执行命令,打印结果
stdin, stdout, stderr = self.ssh_client.exec_command(command)
print(stdout.read().decode())
def ssh_logout(self):
#注销链接
self.ssh_client.close()
if __name__=="__main__":
command = "cd"
ssh = SshClient()
if ssh.ssh_login(host_ip="127.0.0.1", username="zhang", password="123456") == 1000:
ssh.execute_some_command(command)
ssh.ssh_logout()
print("success ssh connent")
else:
print("error connect to host ")
参考文章: