pexpect 记录

#!/usr/bin/python3
#-- coding:utf-8 --

import pexpect
import sys

child = pexpect.spawn('/usr/bin/ssh [email protected]') #spawn主要负责启动和控制子应用程序
fout = open('mylog.txt','wb')
child.logfile = fout
child.expect("password:") #定义子程序输出的匹配规则
child.sendline("123456")
child.expect('#')
child.sendline('ls /home')
child.expect('#')

#!/usr/bin/python3
#-- coding:utf-8 --

import pexpect

child = pexpect.spawn("echo 'foobar'")
print(child.expect(['bar','foo','foobar'])) #当匹配项为列表时,返回的结果为要匹配的字符串中首先出现的那个元素

#!/usr/bin/python3
#-- coding:utf-8 --
import pexpect,sys

child = pexpect.spawn('/usr/bin/ssh [email protected]')
fout = open('mylog.txt2','wb')
child.logfile = fout
child.expect(["password:"])
child.send("123456")
print("before:"+child.before.decode('utf-8'))
print("after:"+child.after.decode('utf-8'))

#!/usr/bin/python3
#-- coding:utf-8 --
from pexpect import pxssh #pxssh是pexpect的派生类
import getpass
try:
s = pxssh.pxssh()
hostname = input('hostname: ')
username = input('username: ')
password = getpass.getpass('password: ')
s.login (hostname, username, password) #建立ssh连接
s.sendline ('uptime') # 执行一个命令
s.prompt() # match the system prompt(提示) 等待系统提示符,用于等待命令执行结束
print(s.before) #打印出现系统提示符之前的命令输出
s.sendline ('ls -l')
s.prompt()
print(s.before)
s.sendline ('df')
s.prompt()
print(s.before)
s.logout() #断开ssh连接
except pxssh.ExceptionPxssh as e:
print("pxssh failed on login.")
print(str(e))

#!/usr/bin/python3
#-- coding:utf-8 --

from future import unicode_literals #指定使用的编码为Unicode

import pexpect
import sys

child = pexpect.spawnu('ftp 192.168.10.78')
child.expect('(?i)name .*: ') #(?i)表示后面的匹配忽略大小写
child.sendline('anonymous')
child.expect('(?i)password')
child.sendline(s='') #表示输入回车
child.expect('ftp> ')
child.sendline('bin') #表示开启二进制传输模式
child.expect('ftp> ')
child.sendline('get anaconda-ks.cfg') #下载文件
child.expect('ftp> ')
sys.stdout.write (child.before) #获取最后一次匹配之前的输出
print("Escape character is '^]'.\n")
sys.stdout.write (child.after)
sys.stdout.flush()
child.interact() # 让出控制权,用户可以手动继续操作,默认输入^]字符退出
child.sendline('bye') #发送bye退出
child.close()

#!/usr/bin/python3
#-- coding:utf-8 --

import pexpect
import sys

ip="192.168.10.67"
user="root"
passwd="123456"
target_file="/root/backup.sql"

child = pexpect.spawn('/usr/bin/ssh', [user+'@'+ip])
fout = open('mylog.txt','wb')
child.logfile = fout

try:
child.expect('(?i)password')
child.sendline(passwd)
child.expect('#')
child.sendline('tar -czf /root/backup.tar.gz '+target_file)
child.expect('#')
print(child.before.decode('utf-8'))
child.sendline('exit')
fout.close()
except EOF:
print("expect EOF")
except TIMEOUT:
print("expect TIMEOUT")

child = pexpect.spawn('/usr/bin/scp', [user+'@'+ip+':/root/backup.tar.gz','/home'])
fout = open('mylog.txt','ab')
child.logfile = fout
try:
child.expect('(?i)password')
child.sendline(passwd)
child.expect(pexpect.EOF)
except EOF:
print("expect EOF")
except TIMEOUT:
print("expect TIMEOUT")

猜你喜欢

转载自blog.51cto.com/xiaoshanzi/2122708