This works on Ubuntu 24.04 host and server
- runs under sudo
- runs multiple lines
- does not require me to enter my sudo password
Some of these came from other answers on SO and on other sites. I did have to play with those answers until it worked as I needed it:
- your_userid: the non-sudo userid on the remote host
- your_remote_host: the ip address or domain of the remote host
- the file secure_sudo_pwd has the sudo password in it
my_cool_sudo_password <= ensure there is newline after this
- the first cat puts the sudo password into the stdin stream and the rest of your commands until "EOF"
- invokes SSH and then cats the stdin into the next command, which is
sudo su -
- the backslash in
\| in required (it's not a markdown for SO posts).
- the prompt prevents most of the initial dump that bash does from showing up
- note that comments in the stdin work correctly, the lines are ignored
cat secure_sudo_pwd - << EOF | ssh $your_userid@$your_remote_host cat \| sudo --prompt="" -S -- su -
hostname
whoami
# echo commented out line
hostname
whoami
echo line1
EOF
typical output:
vm-1 <= my host is a virtualbox running Ubuntu 24.04
root <= confirms that it is running as root
root
vm-1
line1
I have checked as best as I can whether the password or content of this SSH session shows up on the host:
# on the host
cd /var/log
tail -f dmesg syslog auth.log kern.log
There were no indications of "sudo", "hostname", "whoami", or password, etc.
There was an entry in authlog showing an ssh login
Jan 7 12:55:06 vm-1 sshd[12122]: Accepted publickey for xx from 10.0.0.xx port 33698 ssh2: ED25519 SHA256:U24xx