Skip to content

Instantly share code, notes, and snippets.

@mkorthof
Created January 13, 2018 14:16
Show Gist options
  • Save mkorthof/e022f1643a7be0c3b75ce10be212162c to your computer and use it in GitHub Desktop.
Save mkorthof/e022f1643a7be0c3b75ce10be212162c to your computer and use it in GitHub Desktop.
pop3.exp - connects to pop3 server using telnet
#!/usr/bin/expect
proc help {} {
global argv0
puts ""
puts "pop3.exp - connects to pop3 server using telnet"
puts ""
puts "usage: $argv0 <host> <user>"
puts " it will prompt for password"
puts ""
}
set maskpw 1 ;# set to 1 to mask password using asterisks
set interact 1 ;# set to 1 to enable user control after login
set timeout 60
log_user 0
set host [lindex $argv 0]
set user [lindex $argv 1]
set port "110"
if {[llength $argv] == 0} { help; exit 0 }
if { $host == "" || $user == "" } { help; exit 1 }
set buf ""; set output ""
if {[catch {eval spawn telnet $host $port} err]} {
send_user "ERROR: $bin $host $port $err\n"
continue
}
expect {
"Trying *" { set buf "$expect_out(buffer)" }
"Connection to *" { set buf "expect_out(buffer)" }
"telnet: could not resolve *" { send_user "$expect_out(buffer)\n"; exit 1 }
send_user "$buf\n"
}
expect {
-re "\\+OK (POP3|Server) ready" { send_user "$expect_out(buffer)\n"; send "USER $user\r" }
"*Connection closed*" { send_user "$expect_out(buffer)\n"; exit 1 }
}
expect "+OK" {
send_user "$expect_out(buffer)\n"
send_user "\nEnter password: "
if { $maskpw == 1 } { stty -echo }
expect_user -re "(.*)\n"
stty echo
send "PASS $expect_out(1,string)\r"
}
expect {
"PASS *" {
set buf "$expect_out(buffer)"
if { $maskpw == 1 } {
set regex {^[\r\n]{2}?PASS (\S*)[\r\n]{2}?.*}
set passlen "[string length [regsub $regex $buf "\\1"]]"
set output "[regsub $regex $buf [string repeat * $passlen]]"
send_user "$output"
} else {
send_user "$buf"
}
}
"*Connection closed*" { send_user "$expect_out(buffer)\n"; exit 1 }
}
expect {
-re "\\+OK (server ready|Logged in)" {
send_user "\n$expect_out(buffer)\n"
if { $interact == 0 } {
send "QUIT\r"
} else {
send_user "\nENABLING INTERACT...\n"
send_user "POP COMMANDS: STAT, LIST, RETR n, DELE n, RSET, TOP msg n, QUIT\n"
log_user 1
interact
exit 0
}
}
-ex "-ERR LOGIN failed" { send_user -- "$expect_out(buffer)\n"; exit 1 }
"*Connection closed*" { send_user "$expect_out(buffer)\n"; exit 1 }
}
expect {
"+OK *" {
send_user "$expect_out(buffer)\n"
send_user "LOGIN SUCCESS: $host $user\n"
exit 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment