1、paramiko自动登录网络设备抓取配置信息
ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname='192.168.1.2', port=22, username='cisco', password='cisco') client = ssh.invoke_shell() def run_cmd(cmd, endswith): #形参:cmd命令,结束符 buff = '' client.send(cmd) while not buff.endswith(endswith): resp = str(client.recv(1024), 'utf-8') buff += resp return buff res = '' res += run_cmd('enable ', 'Password: ') res += run_cmd('cisco ', '#') res += run_cmd('terminal length 0 ', '#') res += run_cmd('show run ', '#') print(res) ssh.close()
def sshconnect(command,hostname): """ :param command: 格式必需为list :param hostname: 单个主机IP地址 :return: 用户不存在或连接超时返回错误 """ ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(hostname=hostname, port=22, username=USERNAME, password=PASSWORD) except (NoValidConnectionsError,TimeoutError,AuthenticationException) as e: return {'status':False, 'ip': hostname} else: client = ssh.invoke_shell() for i in range(0, len(command)): buff = '' client.send(command[i] + ' ') while not buff.endswith('#'): resp = str(client.recv(1024), 'utf-8') buff += resp ssh.close()
https://github.com/tecstack/forward