直接使用csdn博主你若安好我便天晴的博客的内容,其文写的很详细,很清晰,很易懂。
我在port
有一点点修改,允许在调用的更换其他的端口,原作者应该也是想如此,但是忘记写了。
封装如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| 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,port, password): try: self.ssh_client.set_missing_host_key_policy(AutoAddPolicy()) self.ssh_client.connect(host_ip, port=port, 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 = "pwd" ssh = SshClient() if ssh.ssh_login(host_ip="124.222.83.93",port=22, username="root", password="pengh2()") == 1000: ssh.execute_some_command(command)
|
参考文章
- Python—实现ssh客户端(连接远程服务器)_python ssh连接服务器-CSDN博客