SSH客户端实现方案一,执行远程命令
# -*- coding:utf-8 -*- import paramiko # 先安装pycrypto,再安装paramiko # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在~/.ssh/known_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect(hostname="106.15.88.182", port=22, username="root", password="abc0506ABC=") # 执行命令,不要执行top之类的在不停的刷新的命令(可以执行多条命令,以分号来分隔多条命令) # stdin, stdout, stderr = ssh.exec_command("cd %s;mkdir %s" % ("/www/wwwroot", "aa")) stdin, stdout, stderr = ssh.exec_command("python /www/wwwroot/test.py") stdin.write("终端等待输入...\n") # test.py文件有input()函数,如果不需要与终端交互,则不写这两行 stdin.flush() # 获取命令结果 res, err = stdout.read(), stderr.read() result = res if res else err res = result.decode() res = result.decode("utf-8") res = result.decode(encoding="utf-8") print res # 关闭服务器连接 ssh.close()
SSH客户端实现方案二,执行远程命令
封装之后的使用
import sys,logging from paramiko.client import SSHClient, AutoAddPolicy from paramiko import AuthenticationException from paramiko.ssh_exception import NoValidConnectionsError class SshClient(): def __init__(self): self.ssh_client = SSHClient() def ssh_login(self, host_ip, username, password): try: # 设置允许连接known_hosts文件中的主机(默认连接不在known_hosts文件中的主机会拒绝连接抛出SSHException) 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 = "whoami" # 自己使用ssh时,命令怎么敲的command参数就怎么写 ssh = SshClient() if ssh.ssh_login(host_ip="106.15.88.188", username="root", password="abc0506") == 1000: ssh.execute_some_command(command) ssh.ssh_logout()