Lets learn "How to run commands on remote host"
In this tutorial, we'll learn about how to execute commands on the remote system using SSH. In this, we'll assume the source host (from where'll be running the commands from) is host1 and the destination host is host2 on which we'll be executing the command on.
Running a simple command
[root@host1 ~]# sudo -u root -- ssh host2 touch /tmp/foo
...
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'host2,*.*.*.*' (ECDSA) to the list of known hosts.
root@host2's password:
[root@host1 ~]#
[root@host2 ~]# ls /tmp/foo
/tmp/foo
[root@host2 ~]# ls -ltrh /tmp | grep foo
-rw-rw-r-- 1 root root 0 Oct 3 15:45 foo
Running a complex command
By complex command, I mean running multiple commands in one go separated by &&. One thing to be taken care of while running the complex command is you need to add quotes ("") around the command to run the full command on the destination host.
[root@host1 ~]# sudo -u root -- ssh host2 hostname && hostname
root@host2's password:
host2
host1
[root@host1 ~]# sudo -u root -- ssh host2 "hostname && hostname"
root@host2's password:
host2
host2
You can see in the first scenario second `hostname` ran on the current host (host1) only. But with quotes, the full complex command ran on the remote host only.
HOPE YOU LIKE THIS TUTORIAL. FEEL FREE TO ADD COMMENT BELOW IF YOU HAVE ANY DOUBTS. STAY TUNED FOR MORE TUTORIALS :)
Comments
Post a Comment