How to handle errors from passwd in expect script? - expect

I'm trying to create an expect script to update a user's password non-interactively. New to expect and shell scripting. I want to be able to capture and handle errors encountered. For example, if I'm running passwd normally, and my new password isn't acceptable for some reason, I might see a message like "BAD PASSWORD: The password is too similar to the old one".
The problem is that, in the expect script, after send $new_pswd\r with an invalid password, expect "BAD PASSWORD:*" is failing because the next output from passwd is " ".
I would like to capture the bad passwords and the message so that I can return those to the calling process.
The use case here is to allow individual users who may have multiple accounts to update all their accounts with the same password in one go. This script would be called once for each account.
#!/usr/bin/expect -df
# THIS SCRIPT WON'T WORK
set old_pswd $::env(PSWD1)
set new_pswd $::env(PSWD2)
spawn passwd
expect "*ssword:" { send "$old_pswd\r" }
expect "*ssword:" { send "$new_pswd\r" }
expect {
"*ssword:" {
puts "Expected\r"
send "$new_pswd\r"
exit 0
}
"BAD PASSWORD:*" {
puts "BAD PASSWORD\r"
send \x03
exit 1
}
"*" {
puts "Unexpected\r"
send \x03
puts $expect_out(buffer)
exit 1
}
}

UPDATE: I learned a lot about expect since yesterday and wound up solving the problem and a couple others in the script.
The first problem was that I was expecting the password prompt without a space after the colon, so all subsequent expect commands were trying to match against the as-yet-unconsumed space character, which matched against "*", and terminated the script before passwd ever sent its BAD PASSWORD message.
The second problem was trying to match *ssword: before "BAD PASSWORD". The prompt for new password would always match before the BAD PASSWORD message, because passwd was sending "BAD PASSWORD: message message message\r\nNew password: "
Here is a script that now works and is wrapped in an su. Whatever process is calling this script needs to clean up the environment variables afterward. The idea would be to set those securely in advance so that credentials don't have to be passed on command lines. This script is intended to be called from the user's account once for each other account that belonged to them:
#!/usr/bin/expect -f
# THIS SCRIPT WORKS
set old_pswd $::env(PSWD1)
set new_pswd $::env(PSWD2)
set new_user $::env(USER1)
spawn su $new_user
expect "*ssword: " { send "$old_pswd\r" }
expect "$ " { send "passwd\r" }
expect "*ssword: " { send "$old_pswd\r" }
expect "*ssword: " { send "$new_pswd\r" }
expect {
"BAD PASSWORD: " {
expect {
"dictionary" { set exit_code 1 }
"shorter than" { set exit_code 2 }
"too similar" { set exit_code 3 }
"No password" { set exit_code 4 }
"*" { set exit_code 99 }
}
send \x03
expect "$ " { send "exit\r" }
exit $exit_code
}
"*ssword: " {
send "$new_pswd\r"
expect "$ " { send "exit\r" }
exit 0
}
}

Related

Non-reliable results from Expect when running a remote script

Because my company insists on using sudo I now have to scrap my ssh system I've built for running remote commands.
I have a script that will connect to a server, sudo into the db2 inst owner account and then run a script (previously delivered into /tmp). Maybe 1 in 10 times it will work (outputs 'Hello world' for my test).
Here is the ksh script on the remote server (/tmp/cwow/generic.ksh):
#!/usr/bin/ksh93
echo "Hello world"
[I've also tried adding sleep 5 and wait with mixed results but it doesn't solve the problem]
The expect script I'm running locally is:
#!/usr/bin/expect
set spath /tmp/cwow/generic.ksh
set pass $env(MYEXPECTPASS)
set user $env(MYEXPECTUSER)
if { [llength $argv] != 2 } {
send_user "USAGE: $argv0 host inst\n"
exit
}
set host [lindex $argv 0]
set inst [lindex $argv 1]
set timeout 10
log_user 1
exp_internal 0
eval spawn /usr/bin/ssh -t $user#$host "sudo su - cwow"
expect {
timeout { send_user "TimedOut"; exit }
-glob "assword:" {
send "$pass\r"
expect {
-glob "assword:" {
send "$pass\r"
expect {
-glob " " {
send "/tmp/cwow/generic.ksh\r\n"
expect {
-glob "world" {
send_user "Got it\r"
}
}
}
}
}
}
}
}
I should also note that I never get the 'Got it' message but I don't really need that to work, just curious why it doesn't. What I need to work reliably is for the script to run and, most of the time, it doesn't appear to.
Any ideas for a weak expect user would be greatly appreciated.
(not an answer, just a formatted comment)
You don't need to nest all the expect commands: if you expect a pattern with no action body, the script will continue to the next command. This is more readable, IMO:
expect {
timeout { send_user "TimedOut"; exit }
"assword:"
}
send "$pass\r"
expect "assword:"
send "$pass\r"
expect " "
send "/tmp/cwow/generic.ksh\r"
expect "world"
send_user "Got it\n"
Note, you should send to the spawned process with \r as "hitting Enter". But \n is used for send_user.

how to make command "ps" don't show password in expect script?

I have make an example as below. The password(mingps)is the shell variable. When execute the shell script, in the mean while, execute command "ps -ef", I found the result of "ps" showed the password(mingps). For security reason, I don't want to show the password when execute command "ps -ef". So how to hide it? Thanks in advance.
#!/bin/sh
MalbanIP="XXX.XXX.XXX.XXX"
MalbanLogin="ming"
MalbanPwd="mingps"
MalbanCmd="netstat"
firstTime="true"
/usr/bin/expect <<EOF
set timeout 10
log_user 0
spawn /usr/bin/ssh $MalbanIP -l $MalbanLogin
expect {
-nocase "continue connecting (yes/no)?" {
send "yes\r"
expect "password:" {
send "$MalbanPwd\r"; set firstTime "false"; exp_continue
}
}
"password" {
if {$firstTime == "true"} {
send "$MalbanPwd\r"; set firstTime "false"
} else {
log_user 1; puts stdout "password is wrong"; log_user 0;
exit 1
}
}
}
expect "0-0-3"
log_user 1
send "$MalbanCmd \r"
set results \$expect_out(buffer)
expect "0-0-3" { send "exit\r" }
expect eof
EOF
exit 0
Option 1
The best way is to switch to using RSA keys to log in, as this will enable you to significantly strengthen your overall system security substantially. With that, you can probably avoid using Expect entirely.
Option 2
However, if you can't do that, the key to fixing things is to not pass it as either an argument or an environment variable (since ps can see both with the right options). Instead, you pass the password by writing it into a file and giving the name of that file to the Expect script. The file needs to be in a directory that only the current user can read; chmod go-rx will help there.
MalbanPwdFile=/home/malban/.securedDirectory/examplefile.txt
# Put this just before the spawn
set f [open $MalbanPwdFile]
set MalbanPwd [gets $f]
close $f
You might also need to put a backslash in front of the use of $MalbanPwd so that it doesn't get substituted by the shell script part too early.
Option 3
Or you could stop using that shell wrapper and do everything directly in Tcl/Expect.
#!/usr/bin/expect
set MalbanIP "XXX.XXX.XXX.XXX"
set MalbanLogin "ming"
set MalbanPwd "mingps"
set MalbanCmd "netstat"
set firstTime true
set timeout 10
log_user 0
spawn /usr/bin/ssh $MalbanIP -l $MalbanLogin
expect {
-nocase "continue connecting (yes/no)?" {
send "yes\r"
expect "password:" {
send "$MalbanPwd\r"
set firstTime false
exp_continue
}
}
"password" {
if {$firstTime} {
send "$MalbanPwd\r"
set firstTime false
} else {
log_user 1
puts stdout "password is wrong"
log_user 0
exit 1
}
}
}
expect "0-0-3"
log_user 1
send "$MalbanCmd \r"
set results \$expect_out(buffer)
expect "0-0-3" { send "exit\r" }
expect eof
I suspect that this last option will work best for you in the longer term. It's definitely the simplest one (other than switching to RSA keys, which is what I've got deployed on my own infrastructure) and I think it is going to avoid some subtle bugs that you've got in your current code (due to substitution of variables at the wrong time).

expect script is not sending correct value

I wrote an expect script which will connect to a server and send a password depending on the prompt. The purpose is to update my password on new servers.
Basically, it will connect to a new server, expect to see (current) UNIX password: and then send my initial password. It will then see the 'New password:and 'Retype new password: prompts sending the new password each time.
My script loads these passwords from files into variables $pw1 and $pw2. I have evaluated them and verified that I have the correct values loaded into the variables. However, when I run the script, I am getting a token manipulation error on the initial password which tells me the value being sent is incorrect.
Perhaps my logic is incorrect?
EDIT: I have connected to one server that I'm running the script against and entered the old password exactly as it is in the file that the script loads into $pw2. It is working so I know that the password is not incorrect.
#! /usr/bin/expect --
#exp_internal 1
#set stty_init raw
set timeout 45
set prompt {\$ $}
set file1 [open [lindex $argv 0] r]
set pw1 [exec cat /home/user/bin/.pw1.txt]
set pw2 [exec cat /home/user/bin/.pw2.txt]
#puts $pw1
#puts $pw2
while {[gets $file1 host] != -1} {
puts $host
spawn -noecho ssh -q $host
expect {
"*assword*" {
send -- "$pw1\r"
expect {
$prompt {
send -- exit\r
}
}
send -- exit\r
expect eof
}
-re $prompt {
send -- exit\r
expect eof
}
"(current)*" {
send -- "$pw2\r"
expect "New password"
send -- "$pw1\r"
expect "Retype new password"
send -- "$pw1\r"
puts \r
}
"continue*" {
send "yes\r"
expect {
"current" {
send -- "$pw2\r"
expect "New password"
send -- "$pw1\r"
expect "Retype new password"
send -- "$pw1\r"
puts \r
# expect eof
}
-re $prompt {
send -- exit\r
expect eof
}
}
}
}
}
puts \r
First, I'd like to note that you don't need to nest expect commands: look into the exp_continue command, instead. It will cut your code size in half simply by eliminating duplication.
Second, it looks your logic is, indeed, wrong. The first expect pattern is "*assword*". I would expect this to match when the remote server of your ssh is prompting for the user's current password, and it sends $pw1. However, everywhere else in your code, you seem to be treating $pw2 as the current password, and $pw1 as the new password.
Also, when you rewrite your code using exp_continue to eliminate the duplication and nesting, make sure you re-order your patterns so they're listed in order of most specific to least specific. Otherwise, you'll sometimes find the wrong pattern being matched, and the wrong code being executed.

Remove send command from terminal output while keeping needed output

I am trying to create a script that will log onto a server, run some commands while providing information back to the user.
I can log onto the server fine using the script, my issue is the output I get back. My script is something like this:
#!/bin/bash
/usr/bin/expect << SSHLOGIN
set timeout 600
spawn ssh user#myServer.com
expect {
"Are you sure you want to continue connecting (yes/no)?" {
send "yes\n";exp_continue
}
Password: {
send "$2\n"
}
}
expect {
"# " {
send "echo \"Current Directory is:\" \n"
}
}
expect "# " {
send "pwd \n"
}
expect {
"# " {
send "exit \n"
}
}
wait
SSHLOGIN
& my output is as follows:
spawn ssh user#myServer.com
Password:
You have new mail.
DISPLAY set to user.myServer:0.0
# echo "Current Directory is:"
Current Directory is:
# pwd
/home/user/
The output I am trying to achieve is something like:
spawn ssh user#myServer.com
Password:
You have new mail.
DISPLAY set to user.myServer:0.0
Current Directory is:
/home/user/
I've tried using log_user 0/1, stty etc.. but I can't seem to get it right with those...
Any help would be appreciated.
The problem is that the std output of the spawned process includes both program output and sent commands, the latter just because of echoing from the remote device.
You could manipulate stdout via the log_user command, turning it off while still expecting & capturing, and printing out the output yourself via the "puts" command. Lastly re-enable, if at all needed. The below works because Expect does not read the echoed command until the expect command.
I can't test now so I'll leave you the regexp to match the pwd output (beware of prompts with current paths), but since the point of your question is not the regexp, I figure the following will do for you:
#!/bin/bash
/usr/bin/expect << SSHLOGIN
set timeout 600
spawn ssh user#myServer.com
expect {
"Are you sure you want to continue connecting (yes/no)?" {
send "yes\n";exp_continue
}
Password: {
send "$2\n"
}
}
expect {
"# " {
send "pwd \n"
log_user 0
expect -re "(include_here_between_the_parenthesis_a_regexp_that_matches_your_pwd_output)" {
puts "Current directory is: $expect_out(1,string)"
}
log_user 1
}
expect {
"# " {
send "exit \n"
}
}
wait
SSHLOGIN
As a last comment... why not change the top line to #!/usr/bin/expect and make this an expect script as opposed to a bash one with a here documnet (or whatever that was called)? It's almost pure expect code after all.
Let me know how that goes, and don't forget upvoting or marking the answer if it indeed helped. :-)

Is it possible to access an expect-spawned process from other expect scripts, called in bash

I have an expect script that opens a telnet session and performs the authorization. After the authorization has been performed, I want to be able to call from bash other expect scripts, that perform various actions in the same session.
Is it possible?
Not exactly getting what you want because if you provide some code or script then batter but anyway i just having bash script which only open telnet session which is first part what you want now let me know what next part while gone through script so i can modify my script as you want.
#!/bin/bash
testUserAction()
{
expect<<EOF
set timeout 200
spawn telnet $1
expect "login:"
send "testuser\r"
expect "Password"
send "12345678\r"
;;;;;;;;;;;;;#rest of expect which you want
EOF
}
testUserAction 171.172.12.1
It is possible see below example:
#!/usr/local/bin/expect
set user "user"
set host "host"
set pass "password"
spawn telnet $host
set timeout 10
expect {
timeout {
puts "Unable to connect to $host"
exit 1
}
"login: " {
send -- "$user\r"
exp_continue
}
"assword: " {
send -- "$pass\r"
}
}
#Call the other expect script on host
send -- "./test.exp $user\r"
expect {
"($user)" {
puts "OK got it!"
}
}
And then the test.exp script which should be in users home directory on host
#!/usr/local/bin/expect
set name [lindex $argv 0]
puts "Welcome ($name)"

Resources