发布时间:2019-09-12 07:54:50编辑:auto阅读(1647)
pexpect的使用,
linux主机通过测试
华为交换机的ssh,用不了,郁闷。
ssh -v 查看登录过程
[root@pc0003 glpi_switch_ocs]# cat ssh3.py #!/usr/bin/env python # -*- coding: utf-8 -*- import pexpect import getpass, os def ssh_command (user, host, password, command): ssh_newkey = 'Are you sure you want to continue connecting' child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command)) i = child.expect([pexpect.TIMEOUT, ssh_newkey, 'password: ']) # 如果登录超时,打印出错信息,并退出. if i == 0: # Timeout print 'ERROR!' print 'SSH could not login. Here is what SSH said:' print child.before, child.after return None # 如果 ssh 没有 public key,接受它. if i == 1: # SSH does not have the public key. Just accept it. child.sendline ('yes') child.expect ('password: ') i = child.expect([pexpect.TIMEOUT, 'password: ']) if i == 0: # Timeout print 'SSH could not login. Here is what SSH said:' print child.before, child.after return None child.sendline(password) return child def main (): host = raw_input('Hostname: ') user = raw_input('User: ') password = getpass.getpass() command = raw_input('Enter the command: ') child = ssh_command (user, host, password, command) child.expect(pexpect.EOF) print child.before if __name__ == '__main__': try: main() except Exception, e: print str(e) traceback.print_exc() os._exit(1) [root@pc0003 glpi_switch_ocs]# python ssh3.py Hostname: 172.16.66.132 User: root Password: Enter the command: lsb_release -a No LSB modules are available. Distributor ID: Debian Description: Debian GNU/Linux 7.9 (wheezy) Release: 7.9 Codename: wheezy
paramiko ssh 交互
华为交换机的ssh,还是用不了,更郁闷。
ssh -v 查看登录过程
登录ssh,显示文件,切换目录
import paramiko client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect('172.16.66.132', 22, username='user', password='password ', timeout=4) stdin, stdout, stderr = client.exec_command('ls -l') for std in stdout.readlines(): print std, stdin, stdout, stderr = client.exec_command('cd /etc;pwd') for std in stdout.readlines(): print std, client.close()
输出结果
[root@pc0003 glpi_switch_ocs]# python ssh.py total 12 -rw-r--r-- 1 root root 1542 Oct 21 16:31 ceph.log -rw-r--r-- 1 root root 1645 Oct 21 14:43 release.asc -rw-r--r-- 1 root root 26 Nov 23 10:00 test /etc [root@pc0003 glpi_switch_ocs]#
上一篇: python爬虫的常见方式
下一篇: python 点滴记录1:python没
47848
46402
37290
34738
29321
25977
24922
19955
19549
18032
5796°
6420°
5936°
5965°
7071°
5919°
5950°
6444°
6407°
7786°