import paramiko import json import time import sys import os from paramiko.ssh_exception import NoValidConnectionsError from paramiko.ssh_exception import AuthenticationException class SSHConnection(): def __init__(self, hostname, port, username, password, answering): self.hostname = hostname self.port = port self.username = username self.password = password self.answering = answering def connect(self): self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname=self.hostname, port=self.port, username=self.username, password=self.password) def run(self, input): try: self.connect() except (AuthenticationException, NoValidConnectionsError, TimeoutError) as e: print(e) if self.answering: self.answering_shell(input) else: for cmd in input: self.cmd(cmd) self.close() def cmd(self, input): stdin, stdout, stderr = self.ssh.exec_command(input) print(stdout.read().decode()) def close(self): self.ssh.close() def answering_shell(self, cmds): try: channel = self.ssh.invoke_shell() time.sleep(1) for cmd in cmds: channel.send(cmd.encode()) channel.send(b'\n') time.sleep(1) r = channel.recv(40960).decode() sys.stdout.write(r) channel.close() except Exception as e: print(e) if __name__ == '__main__': config = { 'serverIP': '', 'serverPort': '', 'username': '', 'password': '', 'answering_shell': True, #是否开启应答式Shell(默认开启) #需要输入的命令集合,可多条命令依次执行,直接输入多条命令即可 #'cmds': ''' # ip add # reboot # shutdown # ''' 'cmds': ''' ''' } ip, port, username, password, answering, cmds = \ config['serverIP'], config['serverPort'], config['username'], config['password'], \ config['answering_shell'], config['cmds'] if cmds: cmds = [cmd.strip() for cmd in cmds.split('\n') if cmd.strip()] if not cmds: print('未指定要执行的命令,请在“config”中指定,3秒后退出程序。') time.sleep(3) os._exit(1) if not ip: print('请按下列示例输入服务器IP或者IP+端口号') print('Example: 192.168.1.1') print('Example: 192.168.1.1:8088') ip_port = input('请输入服务器IP:') if ip_port.find(':') > 0 or ip_port.find(':') > 0: ip_port = ip_port.replace(':', ':') ip = ip_port.split(':')[0] port = ip_port.split(':')[1] else: ip = ip_port if not port: port = '22' else: if not port: port = '22' if not username: username = input('请输入用户名:') if not password: password = input('请输入密码:') ssh = SSHConnection(ip, port, username, password, answering) ssh.run(cmds) ssh.close() # dingding(output)