Currently I am using SSHPass
in a script to connect to a remote server:
sshpass -p PASSWORD ssh -o StrictHostKeyChecking=no [email protected]
and to execute any command remotely, I use:
sshpass -p PASSWORD ssh -o StrictHostKeyChecking=no [email protected] "COMMAND"
I am planning to separate the connection step in one script (conn.sh
) and the commands in another (cmd.sh
).
I tried this way:
cmd.sh:
#!/bin/bash
ls -ltr
conn.sh:
#!/bin/bash
sshpass -p PASSWORD ssh -o StrictHostKeyChecking=no [email protected] "$1"
And execution after giving both scripts "chmod a+x":
./conn.sh cmd.sh
But it gave me error:
cmd.sh: command not found
I even tried to replace $1
with the path to cmd.sh
, but it gave me this error:
sh: /home/myhome/cmd.sh: No such file or directory
The reason it fails is that when you run something like
ssh user@remote command
The command
is not only run on the remote machine, it is also searched for on the remote machine. Therefore, when you run ./conn.sh cmd.sh
, you are connecting to the remote and then you are trying to run a script called cmd.sh
on the remote. Since there is no such script (it's stored on your local machine), the execution fails and you see that error.
You can do what you describe by changing your conn.sh
to:
#!/bin/bash
sshpass -p PASSWORD ssh -o StrictHostKeyChecking=no [email protected] \
bash -s < "$1"
And then run
./conn.sh /local/path/to/cmd.sh
That will open a bash shell on the remote machine. The -s
tells bash to read commands from standard input and the < "$1"
provides the 1st argument given to conn.sh
as the input to that bash shell.
Are you sure you need to do this though? What you describe is almost certainly an XY problem. The simple solution is to create the cmd.sh
on the remote server. Then you can do
./conn.sh /remote/path/to/cmd.sh
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments