Paramiko
paramiko模块,基于SSH用于连接远程服务器并执行相关操作。.
远程连接服务器执行上传下载
1 import paramiko 2 class SSH: 3 def __init__(self, host,port,user,pwd): 4 self.host = host 5 self.port = port 6 self.user = user 7 self.pwd = pwd 8 self.transport = None 9 def connect(self): 10 self.transport = paramiko.Transport((self.host, self.port,)) 11 self.transport.connect(username=self.user, password=self.pwd) 12 13 def cmd(self,cmd): 14 ssh = paramiko.SSHClient() 15 ssh._transport = self.transport 16 stdin, stdout, stderr = ssh.exec_command(cmd) 17 return stdout.read() 18 19 def download(self,server_path,local_path): 20 sftp = paramiko.SFTPClient.from_transport(self.transport) 21 # 将location.py 上传至服务器 /tmp/test.py 22 # sftp.put(‘/tmp/location.py‘, ‘/tmp/test.py‘) 23 # 将remove_path 下载到本地 local_path 24 sftp.get(server_path, local_path) 25 26 def upload(self,server_path,local_path): 27 sftp = paramiko.SFTPClient.from_transport(self.transport) 28 # 将location.py 上传至服务器 /tmp/test.py 29 # sftp.put(‘/tmp/location.py‘, ‘/tmp/test.py‘) 30 # 将remove_path 下载到本地 local_path 31 sftp.put(local_path, server_path) 32 33 34 def close(self): 35 self.transport.close() 36 37 obj = SSH(‘192.168.100.1‘,22,‘root‘,‘123‘) 38 obj.connect() 39 # v = obj.cmd(‘ls‘) 40 v = obj.cmd(‘df -h‘) 41 print(v) 42 obj.close()
1 import paramiko 2 import uuid 3 4 class SSHConnection(object): 5 6 def __init__(self, host=‘192.168.11.61‘, port=22, username=‘alex‘,pwd=‘alex3714‘): 7 self.host = host 8 self.port = port 9 self.username = username 10 self.pwd = pwd 11 self.__k = None 12 13 def run(self): 14 self.connect() 15 pass 16 self.close() 17 18 def connect(self): 19 transport = paramiko.Transport((self.host,self.port)) 20 transport.connect(username=self.username,password=self.pwd) 21 self.__transport = transport 22 23 def close(self): 24 self.__transport.close() 25 26 def cmd(self, command): 27 ssh = paramiko.SSHClient() 28 ssh._transport = self.__transport 29 # 执行命令 30 stdin, stdout, stderr = ssh.exec_command(command) 31 # 获取命令结果 32 result = stdout.read() 33 return result 34 35 def upload(self,local_path, target_path): 36 # 连接,上传 37 sftp = paramiko.SFTPClient.from_transport(self.__transport) 38 # 将location.py 上传至服务器 /tmp/test.py 39 sftp.put(local_path, target_path) 40 41 ssh = SSHConnection() 42 ssh.connect() 43 r1 = ssh.cmd(‘df‘) 44 ssh.upload(‘s2.py‘, "/home/alex/s7.py") 45 ssh.close() 46 47 Demo
堡垒机流程
- 管理员为用户在服务器上创建账号(将公钥放置服务器,或者使用用户名密码)
- 用户登陆堡垒机,输入堡垒机用户名密码,现实当前用户管理的服务器列表
- 用户选择服务器,并自动登陆
- 执行操作并同时将用户操作记录
完整版
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import paramiko 4 import sys 5 import os 6 import socket 7 import getpass 8 import termios 9 import tty 10 import select 11 from paramiko.py3compat import u 12 13 14 def interactive_shell(chan): 15 # 获取原tty属性 16 oldtty = termios.tcgetattr(sys.stdin) 17 try: 18 # 为tty设置新属性 19 # 默认当前tty设备属性: 20 # 输入一行回车,执行 21 # CTRL+C 进程退出,遇到特殊字符,特殊处理。 22 23 # 这是为原始模式,不认识所有特殊符号 24 # 放置特殊字符应用在当前终端,如此设置,将所有的用户输入均发送到远程服务器 25 tty.setraw(sys.stdin.fileno()) 26 tty.setcbreak(sys.stdin.fileno()) 27 chan.settimeout(0.0) 28 29 log = open(‘handle.log‘, ‘a+‘, encoding=‘utf-8‘) 30 flag = False 31 temp_list = [] 32 33 while True: 34 r, w, e = select.select([chan, sys.stdin], [], []) 35 if chan in r: 36 try: 37 x = u(chan.recv(1024)) 38 if len(x) == 0: 39 sys.stdout.write(‘\r\n*** EOF\r\n‘) 40 break 41 # 如果用户上一次点击的是tab键,则获取返回的内容写入在记录中 42 if flag: 43 if x.startswith(‘\r\n‘): 44 pass 45 else: 46 temp_list.append(x) 47 flag = False 48 sys.stdout.write(x) 49 sys.stdout.flush() 50 except socket.timeout: 51 pass 52 if sys.stdin in r: 53 # 读取用户在终端数据每一个字符 54 x = sys.stdin.read(1) 55 if len(x) == 0: 56 break 57 # 如果用户点击TAB键 58 if x == ‘\t‘: 59 flag = True 60 else: 61 # 未点击TAB键,则将每个操作字符记录添加到列表中,以便之后写入文件 62 temp_list.append(x) 63 64 # 如果用户敲回车,则将操作记录写入文件 65 if x == ‘\r‘: 66 log.write(‘‘.join(temp_list)) 67 log.flush() 68 temp_list.clear() 69 chan.send(x) 70 71 finally: 72 # 重新设置终端属性 73 termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty) 74 75 76 def run(): 77 db_dict = { 78 ‘c1.salt.com‘: { 79 ‘root‘: {‘user‘: ‘root‘, ‘auth‘: ‘r‘, "cert": ‘key路径‘}, 80 ‘alex‘: {‘user‘: ‘alex‘, ‘auth‘: ‘p‘, "cert": ‘密码‘}, 81 }, 82 ‘c2.salt.com‘: { 83 ‘root‘: {‘user‘: ‘root‘, ‘auth‘: ‘r‘, "cert": ‘key路径‘}, 84 ‘alex‘: {‘user‘: ‘alex‘, ‘auth‘: ‘p‘, "cert": ‘密码‘}, 85 }, 86 87 } 88 89 for row in db_dict.keys(): 90 print(row) 91 92 hostname = input(‘请选择主机: ‘) 93 tran = paramiko.Transport((hostname, 22,)) 94 tran.start_client() 95 96 for item in db_dict[hostname].keys(): 97 print(item) 98 99 username = input(‘请输入用户: ‘) 100 101 user_dict = db_dict[hostname][username] 102 if username[‘auth‘] == ‘r‘: 103 key = paramiko.RSAKey.from_private_key_file(user_dict[‘cert‘]) 104 tran.auth_publickey(username, key) 105 else: 106 pw = user_dict[‘cert‘] 107 tran.auth_password(username, pw) 108 109 # 打开一个通道 110 chan = tran.open_session() 111 # 获取一个终端 112 chan.get_pty() 113 # 激活器 114 chan.invoke_shell() 115 116 interactive_shell(chan) 117 118 chan.close() 119 tran.close() 120 121 122 if __name__ == ‘__main__‘: 123 run() 124 125 提示用户选择主机和用户(记录操作日志)
允许用户选择主机
时间: 2024-11-05 12:24:32