0

My bash code is:

  1 #!/bash/sh
  2 set -e
  3 USER="admin"
  4 HOST="1.2.3.4"
  5 PASSWORD="$(cat password.txt)"
  6 
  7 sshpass -p"$PASSWORD" ssh -t $USER@$HOST "/usr/bin/sudo bash -c 'sudo ls 2>&1; echo \"testing\";sudo ls src 2>&1;exit;'" >> log.txt
  8 
  9 echo "------------------------------Another Method ----------------------------------------"
 10 sshpass -p"$PASSWORD" ssh -t $USER@$HOST << EOF
 11 echo "....1...."
 12 sudo ls 2>&1
 13 echo "....2...."
 14 ls src 2>&1
 15 sudo echo "....3...."
 16 exit
 17 EOF

Line 7 can run multiple commands with sudo and print info to log.txt, Line 9-> Line 17 cannot. But I prefer to use Line9 to 17, because the commands I would like to run may contain nested control statements (such as if-else-fi). I have no idea how to do it in line 7. How to make line 9 to line 17 run multiple commands with sudo and print to local log.txt?

Part of screen output is:

....1....
sudo: no tty present and no askpass program specified
sudo: pam_authenticate: User not known to the underlying authentication module
....2....
tmp
....3....

Any help is welcome. Thanks.

2
  • Would expect(1) be useful to you ?
    – user9517
    Jan 15, 2016 at 17:03
  • create is bash script, copy it to the remote machine and run it there. Doing such harakiri is not worth the effort.
    – Jakuje
    Jan 15, 2016 at 17:44

1 Answer 1

1

You seem to be unaware that you can add >> log.txt after the first EOF.

sshpass -p"$PASSWORD" ssh -t $USER@$HOST <<'EOF' >>log.txt
 echo "....1...."
 sudo ls 2>&1
 : etc     
EOF

You can put in the same commands in both variants (newline or semicolon separated) though proper quoting is slightly harder in the first case (not in the second! Though I added quotes around 'EOF' to prevent the shell from interpolating variables etc in the here document; if you need the shell to do that, you'll need to revert that change).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .