-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh_paramiko.py
64 lines (58 loc) · 2.31 KB
/
ssh_paramiko.py
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import logging
import sys
from paramiko import AuthenticationException
from paramiko.client import SSHClient, AutoAddPolicy
from paramiko.ssh_exception import NoValidConnectionsError
import psutil
class MySshClient():
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:
logging.warning('unknow error')
print("Unexpected error:", sys.exc_info()[0])
return 1003
return 1000
# 此函数用于执行command参数中的命令并打印命令执行结果
def execute_some_command(self,command):
stdin, stdout, stderr = self.ssh_client.exec_command(command)
str1 = stdout.read().decode()
f1 = str1[0:5]
print(f1)
f = open(f1, 'r+')
print(f.read())
# 此函数用于退出登录
def ssh_logout(self):
logging.warning('will exit host')
self.ssh_client.close()
if __name__ == '__main__':
# 远程主机IP
# host_ip = '192.168.217.136'
host_ip = '192.168.217.129'
# 远程主机用户名
# username = 'python'
username = 'hairy'
# 远程主机密码
password = '308301'
# 要执行的shell命令;换成自己想要执行的命令
# 自己使用ssh时,命令怎么敲的command参数就怎么写
command = "ls"
# command = psutil.cpu_times()
# 实例化
my_ssh_client = MySshClient()
# 登录,如果返回结果为1000,那么执行命令,然后退出
if my_ssh_client.ssh_login(host_ip,username,password) == 1000:
logging.warning("{host_ip}-login success, will execute command:{command}")
my_ssh_client.execute_some_command(command)
my_ssh_client.ssh_logout()