Home » Linux » linux execute command remotely

linux execute command remotely

Posted by: admin November 29, 2017 Leave a comment

Questions:

how do I execute command/script on a remote linux box?
say I want to do service tomcat start on box b from box a.

Answers:

I guess ssh is the best secured way for this, for example :

ssh -OPTIONS -p SSH_PORT [email protected]_server "remote_command1; remote_command2; remote_script.sh"  

where the OPTIONS have to be deployed according to your specific needs (for example, binding to ipv4 only) and your remote command could be starting your tomcat daemon.

Note:
if you do not want to be prompt at every ssh run, also have a look to ssh-agent, and optionnaly to keychain if your system allows it. Key is… to understand the keys exchange process. Take a careful look to ssh_config (eg ssh client config) and sshd_config (eg ssh server config). Config file names depends on your system, anyway you’ll find them somewhere like /etc/sshd_config. Ideally do not run ssh as root obviously but with a dedicated user on both servers.

Some extra docs over the source project main pages :

ssh and ssh-agent
man ssh (RMF !)
http://www.snailbook.com/index.html
https://help.ubuntu.com/community/SSH/OpenSSH/Configuring
http://sourceforge.net/apps/trac/sourceforge/wiki/SSH%20key%20fingerprints

keychain
http://www.gentoo.org/doc/en/keychain-guide.xml

Questions:
Answers:
 ssh [email protected] 'bash -s' < local_script.sh

or you can just

 ssh [email protected] "remote command to run" 

Questions:
Answers:

I think this article explains well:

Running Commands on a Remote Linux / UNIX Host

Google is your best friend 😉

Questions:
Answers:

If you don’t want to deal with security and want to make it as exposed (aka “convenient”) as possible for short term, and|or don’t have ssh/telnet or key generation on all your hosts, you can can hack a one-liner together with netcat. Write a command to your target computer’s port over the network and it will run it. Then you can block access to that port to a few “trusted” users or wrap it in a script that only allows certain commands to run. And use a low privilege user.

on the server

mkfifo /tmp/netfifo; nc -lk 4201 0</tmp/netfifo | bash -e &>/tmp/netfifo

This one liner reads whatever string you send into that port and pipes it into bash to be executed. stderr & stdout are dumped back into netfifo and sent back to the connecting host via nc.

on the client

To run a command remotely:
echo "ls" | nc HOST 4201