Linux Expexct and Python pexepct
[DESCRIPTION]:
Expect is a tool for automating interative applications such as ssh,scp,su root,etc.Expect really makes this stuff trivial. Expect is also useful for testing these same applications. And by adding Tk, you can also wrap interactive applications in X11 GUIs.Expect can make easy all sorts of tasks that are prohibitively difficult with anything else. You will find that Expect is an absolutely invaluable tool - using it, you will be able to automate tasks that you’ve never even thought of before - and you’ll be able to do this automation quickly and easily.
How to use:
- shell call expect -c
- expect one command file
API Document url:
http://www.tcl.tk/man/expect5.31/expect.1.html
Demo:
Demo1:use shell to call linux scp
#!/bin/bash
dt="$(date +%Y.%m.%d)"
echo $dt
src=/mnt/$1/Day
#dt=$(ls $src | grep 2017)
dsc=$HOME"/kdb_data"$src
mkdir -p $dsc
for i in $dt
do
echo $i
expect -c "
spawn scp -r data@192.168.1.1:$src/$i $dsc/
expect {
\"*assword\" {set timeout 300; send \"123456\r\";}
\"yes/no\" {send \"yes\r\"; exp_continue;}
}
expect eof"
done
Demo2:use expect to call scp command file
expect demo2.sh
#file:demo2.sh
#!/usr/bin/expect
spawn scp -r data@192.168.1.1:/home/data/process.csv .
expect {
"*assword" {set timeout 300; send "123456\r";}
"yes/no" {send "yes\r"; exp_continue;}
}
expect eof
Demo3: The simplest ssh login
spawn ssh root@192.168.1.10
expect "*password:"
send "123456\r"
expect "*#"
interact
Demo4: more common ssh login demo
#yum install expect
#!/usr/bin/expect -f
set ip 192.168.1.10
set password 123456
set timeout 10
spawn ssh root@$ip
expect {
"*yes/no" { send "yes\r"; exp_continue}
"*password:" { send "$password\r" }
}
expect "#*"
send "pwd\r"
send "exit\r"
expect eof
Demo5:using expect to login root
#!/usr/bin/expect
set timeout 20
spawn su
expect "Password:"
send "mycap123\r"
#send "mycap123\n"
expect "#"
send "ls ~ >/tmp/1\r"
expect "#"
send "ls\r"
expect "#"
#interact
pexpect
Pexpect makes Python a better tool for controlling other applications.
Pexpect is a pure Python module for spawning child applications; controlling them; and responding to expected patterns in their output. Pexpect works like Don Libes’ Expect. Pexpect allows your script to spawn a child application and control it as if a human were typing commands.
Pexpect can be used for automating interactive applications such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup scripts for duplicating software package installations on different servers. It can be used for automated software testing. Pexpect is in the spirit of Don Libes’ Expect, but Pexpect is pure Python. Unlike other Expect-like modules for Python, Pexpect does not require TCL or Expect nor does it require C extensions to be compiled. It should work on any platform that supports the standard Python pty module. The Pexpect interface was designed to be easy to use.
API Document url:
http://pexpect.readthedocs.io/en/stable/
Demo1:
def sshcmd(ip,user,password,cmd):
try:
ssh = pxssh.pxssh()
ssh.login (ip,user, password)
ssh.sendline(cmd)
ssh.prompt()
a= ssh.before
print '--------------'+a+'----------------'
#print map(lambda x: x.strip() ,a.split('\n'))
ssh.logout()
return a
except pxssh.ExceptionPxssh,e:
print "pxssh failed on login."
print str(e)
Demo2
def ipmap(ip):
if ip=='192.168.1.2':
return ['data','111111','./start_command_list2.sh']
if ip=='192.168.1.3':
return ['data','123456','./start_command_list2.sh']
if ip=='192.168.1.4':
return ['mycapitaltrade','123456','./start_command_list_debug.sh']
def kill(ip,user,password):
cmd='pgrep start_command| xargs kill -9;pgrep V26| xargs kill -9'
sshcmd(ip,user,password,cmd)
def kill(ip):
kill(ip,ipmap(ip)[0],ipmap(ip)[1])
def killAll():
for x in iplist:
kill(x)
Demo3:
import pexpect
def copyfile():
child = pexpect.spawn('scp tee.tee data@192.168.1.44:/home/data/')
child.expect('password:')
child.sendline('mycap123')
child.expect('$')
child.interact()
try:
copyfile()
except OSError:
print "os error!"
def copyfile(ip,name,password,soursepath,targetpath):
try:
child = pexpect.spawn('scp tee.tee data@192.168.1.44:/home/data/')
child.expect('password:')
child.sendline('mycap123')
child.expect('$')
child.interact()
except OSError:
print 'os error!'
Demo4:git
def git_add_commit(path):
#os.system('git status')
os.system ('git add '+path+'word.txt')
os.system('git status')
os.system('git commit -m "test my code"')
print 'commit OK!'
def git_pull(path):
cmd='git pull -r'
child=pexpect.spawn(cmd)
i=child.expect(["Username for 'https://git.oschina.net':","$"])
if i==0:
child.sendline('*********')
child.expect("Password for 'https://**********@git.oschina.net':")
child.sendline('**********')
child.interact()
print 'git pull -r OK ,use username and password'
elif i==1:
print 'git pull -r OK!without username and password'
child.interact()
def git_push(path):
cmd='git push origin master'
child=pexpect.spawn(cmd)
i=child.expect(["Username for 'https://git.oschina.net':","[$]"])
# i=child.expect("Username for 'https://git.oschina.net':")
if i==0:
child.sendline('*********')
child.expect("Password for 'https://**********@git.oschina.net':")
child.sendline('********')
child.interact()
print 'git push OK ,use username and password'
elif i==1:
print 'git pull OK!without username and password'
child.interact()