Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5376437
  • 博文数量: 1144
  • 博客积分: 11974
  • 博客等级: 上将
  • 技术积分: 12312
  • 用 户 组: 普通用户
  • 注册时间: 2005-04-13 20:06
文章存档

2017年(2)

2016年(14)

2015年(10)

2014年(28)

2013年(23)

2012年(29)

2011年(53)

2010年(86)

2009年(83)

2008年(43)

2007年(153)

2006年(575)

2005年(45)

分类: LINUX

2007-06-21 10:55:14

 

使用expect实现ssh自动交互
周五, 2006-12-22 08:58 — zhigang
下面是使用expect实现的自动远端命令执行的脚本ssh-exec:

#!/bin/sh

# \

exec expect -- "$0" ${1+"$@"}

# ssh-exec host user password command


# execute command on remote host


exp_version -exit 5.0

set ERR_PERMISSION_DENIED 1
set ERR_DIR_OR_FILE_NOT_EXIST 2
set ERR_TIMEOUT 3
set ERR_CONNECTION_REFUSED 4
set ERR_INVALID_ARGUMENT 5

proc auth_trans {password} {
    upvar #0 ERR_PERMISSION_DENIED ERR_PERMISSION_DENIED

    upvar #0 ERR_DIR_OR_FILE_NOT_EXIST ERR_DIR_OR_FILE_NOT_EXIST


    send "$password\r"
    expect {
    #password not correct

    "Permission denied, please try again." {
        exit $ERR_PERMISSION_DENIED
    }
    # ...transmission goes after...

    -re "Is a directory|No such file or directory" {
        exit $ERR_DIR_OR_FILE_NOT_EXIST
    }
    -re "KB/s|MB/s" {
        set timeout -1
        expect eof
        }
    }
}

if {$argc!=2} {
    send_user "usage: remote-exec command password\n"
    send_user " command should be quoted.\n"
    send_user " Eg. remote-exec \"ssh ls\\; echo done\" password\n"
    send_user " or: remote-exec \"scp /local-file :/remote-file\" password\n"
    exit $ERR_INVALID_ARGUMENT
}

set cmd [lindex $argv 0]
set password [lindex $argv 1]

eval spawn $cmd

#timeout in sec, default 10

set timeout 30

expect {
    #first connect, no public key in ~/.ssh/known_hosts

    "Are you sure you want to continue connecting (yes/no)?" {
        send "yes\r"
        expect "password:"
        auth_trans $password
    }
    #already has public key in ~/.ssh/known_hosts

    "password:" {
        auth_trans $password
    }

    #user equivalence already established, no password is necessary

    -re "kB/s|MB/s" {
        set timeout -1
        expect eof
    }
    -re "Is a directory|No such file or directory" {
        expect eof
        exit $ERR_DIR_OR_FILE_NOT_EXIST
    }
    "Connection refused" {
        expect eof
        exit $ERR_CONNECTION_REFUSED
    }
    #connetion error

    timeout {
        exit $ERR_TIMEOUT
    }
}

阅读(3518) | 评论(0) | 转发(0) |
0

上一篇:autoexpect介绍

下一篇:kibitz shell交互软件

给主人留下些什么吧!~~