Search code examples
sshftpexpectsshfs

Trying to send passwrod via expect script in sshfs


I have server that has 2fa and does not allow login using ssh keys. I want to connect via FTP, I am using sshfs. Normal sshfs user@host:/remote/ /local/ works fine. But I wanted to pass the passwrod using expect (-o password_stdin does not work for me).

I have defined the function in .bashrc

function mount_sshfs_with_2fa() {

  # Get the FTP password from the encrypted file
  local password=$(gpg --decrypt encrypted_password.txt)

  # Prompt for verification code
  read -p "Verification code: " otp
  echo $otp

  expect << EOF
    spawn sshfs user@host:/remote/ /local/
    expect -re "code:"
    send -- "$otp\r"
    send_user "Verification code: $otp\n"
    expect -re "Password:"
    send -- "$password\r"
    send_user "Password: $password\n"

EOF
}

It does not give any error but does not mount either. Please tell me what's wrong.

debug

expect -d gives

Verification code: 325776
325776
expect version 5.45.4
argv[0] = expect  argv[1] = -d  
set argc 0
set argv0 "expect"
set argv ""
executing commands from command file
spawn sshfs user@host:/remote/ /local/
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {153497}

expect: does "" (spawn_id exp4) match glob pattern "code:"? no
Verification code: 
expect: does "\rVerification code: " (spawn_id exp4) match glob pattern "code:"? yes
expect: set expect_out(0,string) "code:"
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) "\rVerification code:"
send: sending "325776\r" to { exp4 }

expect: does " " (spawn_id exp4) match glob pattern "assword:"? no


expect: does " \r\n" (spawn_id exp4) match glob pattern "assword:"? no
Password: 
expect: does " \r\n\rPassword: " (spawn_id exp4) match glob pattern "assword:"? yes
expect: set expect_out(0,string) "assword:"
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) " \r\n\rPassword:"
send: sending "(my password)\r" to { exp4 }

update 2 Instead of here-code the following also does not work

expect -c "
    spawn sshfs user@host:/remote/ /local/
    expect "code:"
    send -- "$otp\r"
    expect "assword:"
    send -- "$password\r"
    interact
  "

Is expect something serious or just time waste? I have seen multiple solutions that worked for others gave me error! For example, interact does not work inside expect here-code?


Solution

  • Most probably it's killed by SIGHUP. Try like this:

    expect << EOF
        spawn -ignore SIGHUP sshfs user@host:/remote/ /local/
    
        set timeout -1
    
        expect -re "code:"
        send -- "$otp\r"
        expect -re "Password:"
        send -- "$password\r"
    
        expect eof
        sleep 1
    EOF