Linux Expexct and Python pexepct

本文介绍如何利用Expect和Pexpect工具简化SSH登录及SCP文件传输等交互式任务的自动化处理过程。通过具体示例展示了如何编写脚本来实现自动化的SSH登录验证、SCP文件传输等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

  1. shell call expect -c
  2. 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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值