Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script execute commands after ssh

Tags:

bash

ssh

centos

I am trying to execute a few commands via my first script but it's not working.

#!/bin/bash

#connect to server
echo "Connecting to the server..."

ssh -t root@IP '

    #switch user to deploy
    su - deploy

    #switch path
    echo "Switching the path"
    cd /var/www/deploys/bin/app/config

    #run deploy script
    echo "Running deploy script"

    /usr/local/bin/cap -S env=prod deploy

    #restart apache
    sudo /bin/systemctl restart  httpd.service

    bash -l
'

What is happening? I am successfully connected to the server, the user is changed and then I don't see nothing happening. When I press ctrl + c just like that in terminal, some output from the command that should be executed appears but there are some errors.

Why I don't see everything what is happening in terminal after launching the script? Am I doing it the wrong way?

BTW: when I try connect manually and run the commands myself, everything is working nicely.

Using CentOS 7.

like image 241
Lukas Lukac Avatar asked Oct 17 '14 23:10

Lukas Lukac


People also ask

How do I run a script after ssh?

If you want this for a single user, use ~/. ssh/rc . For execution of a script during logon, add it as a call from within the /etc/profile script. This is executed for every logon, not only for ssh logons.

Can you ssh in a bash script?

Bash script SSH is a common tool for Linux users. It is needed when you want to run a command from a local server or a Linux workstation. SSH is also used to access local Bash scripts from a local or remote server.

How do I run a command through ssh?

Run the command "ssh username@host" to log in to the system. At the command prompt, run "top" to view process activity on the remote system. Exit top and be dropped to the remote command line. Type "Exit" to close the command.


1 Answers

Clean way to login through ssh and excecute a set of commands is

ssh user@ip << EOF
   #some commands
EOF

here EOF acts as the delimitter for the command list

the script can be modified as

ssh -t root@IP << EOF

    #switch user to deploy
    su - deploy

    #switch path
    echo "Switching the path"
    cd /var/www/deploys/bin/app/config

    #run deploy script
    echo "Running deploy script"

    /usr/local/bin/cap -S env=prod deploy

    #restart apache
    sudo /bin/systemctl restart  httpd.service

    bash -l
EOF

will excecutes the command and closes the connection there after

like image 86
nu11p01n73R Avatar answered Oct 12 '22 11:10

nu11p01n73R