Shell脚本是系统日常管理中重要的工具,可以实现循环、判断等控制,但无法实现交互式操作。Expect弥补了这个缺陷,成为高效的系统和网络管理中的重要工具。下面的一个小脚本实现了,自动生成公钥、私钥对,并将产生的公钥上传到目标服务器,实现身份认证。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | #!/usr/bin/expect # Createkeypair.exp # Usage: ./createkeypair host-ip username user-password # Exist & print error message if there are not 3 parameters if { $argc != 3 } { puts stderr "usage: createkeypair host-ip username user-password\n" exit 1 } # Configure the parameter # set timeout=60 set timeout 60 # Set 1st parameter as host ip set host [lindex $argv 0] # Set login name set name [lindex $argv 1] # Set login user's password set password [lindex $argv 2] # Create .ssh directory and generate the key pair if { $name == "root" } { if { ![file isdirectory "/$name/.ssh"] } { send [ exec mkdir /$name/.ssh ] } spawn ssh-keygen -t rsa -f /$name/.ssh/id_rsa } else { if { ![file isdirectory "/home/$name/.ssh"] } { send [ exec mkdir /home/$name/.ssh ] } spawn ssh-keygen -t rsa -f /home/$name/.ssh/id_rsa } expect { "(y/n)?" { send "yes\n" expect "passphrase" send "\n" expect "passphrase again:" send "\n" } "passphrase" { send "\n" expect "passphrase again:" send "\n" } } expect "#" # send the generated public key to the destination host if { $name == "root"} { spawn scp /$name/.ssh/id_rsa.pub $name@$host:/tmp } else { spawn scp /home/$name/.ssh/id_rsa.pub $name@$host:/tmp } expect { "(yes/no)?" { send "yes\n" expect "assword:" send "$password\n" } "assword:" { send "$password\n" } } expect "100%" # Add public key to the authenrized file spawn ssh $host -l $name expect "assword:" send "$password\n" expect "#" if { $name == "root"} { send "cat /tmp/id_rsa.pub >> /root/.ssh/authorized_keys\n" } else { send "cat /tmp/id_rsa.pub >> /home/$name/.ssh/authorized_keys\n" } expect "#" send "exit\n" expect "#" # Test auto login without password spawn ssh $host -l $name expect { "Last login" { send_user "Successfully to login the server!" } "assword:" { send_user "failed to login the server!" } } send "ls\n" expect "#" send "exit\n" expect eof |