Run SSH on Jenkins from file in Git - shell

I have a file on Git with the following shell script
File Name = Job.sh
echo "Warehouse script starting"
ssh -n username#server_name "mkdir -p ~/directory_name/folder_name/file_name"
Under Execute Shell in Jenkins I am running -
sh job.sh
The echo command gets printed in the console. But the job is not doing ssh into username#server_name and creating the directory. Appreciate any feedback.

Try the same command when connected directly to the Jenkins agent (using the account used by Jenkins on that agent)
The goal is to check if that user (on that server agent) does have the right pubic/private key pair in its $HOME/.ssh folder.
And double-check the public key is in servername:~username/.ssh/authorized_keys.
Make sure the private key is not encrypted, to avoid having to deal with ssh-agent and passphrase caching. At least for now, for testing your setup.
Note: the -n option (preventing to read from stdin) is usually for ssh commands executed in the background. You might not need it in your case.
Try also to add #!/bin/bash -x at the beginning of your script (assuming you do have a bash) in order to print all lines executed.

Related

How to ssh into remote linux server using username / ip address and password from window using shell script?

What I am trying to do is to login to remote Linux server using SSH from my Windows machine by running a shell script via git bash.
I would like to write a script which will be used by an user with basic IT knowledge. This script will execute a bunch of commands on the remote machine, so it does need to establish a SSH connection.
What I have tried to write in this script so far is:
ssh username#ip <password>
EDIT: You should consider installing Jenkins on the remote system.
Running a command on a remote system can be done via:
ssh user#host command arg1 arg2
If you omit the password, a password prompt will appear, to get around the password prompt, you should consider setting passwordless SSH login. https://askubuntu.com/questions/46930/how-can-i-set-up-password-less-ssh-login
Rephrasing what you said, you want to write a script (namely script1.sh) which does the following (in this order):
Start a ssh connection with a remote
Execute some commands, possibly written in another script (namely script2.sh)
Close the connection / Keep it open for additional command line commands
If you want to put the remote commands on script2.sh instead of listing them in script1.sh, you need to consider that script2.sh must be on the remote server. If not, then you may consider to delegate to script1.sh the creation/copy of script2.sh on the remote machine. You may copy it in a temporary folder.
In this case, my suggestion is to write script1.sh as follows:
Copy of script2.sh with
scp /path/to/local/script2.sh user#host:/path/to/remote/script2.sh
Switch bash sheel to remote shell with
ssh user#host
Execution of script2.sh
sh /path/to/remote/script2.sh
Instead, if you prefer to list everything in just one script file, you may want to write:
Switch bash sheel to remote shell with
ssh user#host
Execution of commands
echo "This command has been executed on the remote server"
echo "This command has also been executed on the remote server"
..
Possibly closing the SSH connection to prevent that the user execute additional commands
You may consider to copy the ssh-keys on the remote server so to avoid password prompts. More information here.

Jenkins Execute shell is failed after executing ssh to a remote server

I am creating a Jenkins job in which am running a ssh command to execute a script for comparing two folders using diff command on a remote server. Script is running fine, output file is getting created. But after this command Jenkins execute shell block is failed.
Command:
ssh -T user#dtest.com "bash /tmp/sample.sh" >> result.txt
Log:
ssh -T user#dtest.com "bash /tmp/sample.sh" >> result.txt
stdin: is not a tty
"Execute shell" is marked as failure
I am not sure what sample.sh is supposed to do, but I understand that you are trying to capture what is logged by this script.
I would try several solutions:
ssh -T user#dtest.com "bash /tmp/sample.sh >> result.txt"
This should save your output in your remote server. Then you could copy this file from remote to local using:
scp user#dtest.com:/remote/dir/result.txt /local/dir/
More context: Copying files from server to local computer using ssh
If you are choosing this solution, you could also consider to write your result.txt directly from your script, and keep the console output for important logging purpose.
Another Solution I could think of would be to use
ssh user#dtest.com "bash /tmp/sample.sh" > result.txt
With this solution you will redirect your output directly to your local machine.
But you will need to delete the ssh "-T" option. And you will run into other problems with Jenkins. So this might not fit you.
ssh -T Disables pseudo-tty allocation, what sounds like your problem's root cause. (https://docs.oracle.com/cd/E36784_01/html/E36870/ssh-1.html)

How to return to the script once sudo is done

I am on a server and running a script file that has following code.
ssh username#servername
sudo su - root
cd /abc/xyz
mkdir asdfg
I am able to ssh... but then the next command is not working.. the script is not sudo-ing. any idea?
Edit: Able to create a mech id and then do the things.. though still looking for the answer to above question :|
First of all your command will "stuck" on the first line because it will go into an interactive mode. The ssh command will require a password to be provided by a user (unless there is an sshkey being used) . And if the ssh is logged into the remote server then it will wait for user commands from standard input.
Secondly the lines following the ssh command will be executed only when the first process has exited. This is why your script is not "sudoing" - it's waiting for the ssh to end.
So if your point is to run a command on a remote server then put the command as a parameter into the same line as ssh connection. In your case:
ssh user#server sudo su - root
But this will not be of satisfaction for you. I suggest you create a script of what you want to execute on the remote server and then execute the script.
ssh user#server scriptName
The sudo thing here is very tricky because again your script might get stuck in the interactive mode waiting for a password to be inserted so I suggest you think again on the basis of the script.
mb47!
You want to run the script on the remote computer, correct?
On the remote machine, create a file containing the commands you would like to execute.
Then, on the other machine, run ssh user#machine /path/to/script/you/created/earlier
I hope this helps!
ALinuxLover

SSH : Remotely run a script and stay there

I wish to run a script on the remote system and then wish to stay there.
Running following script:-
ssh user#remote logs.sh
This do run the script but after that I am back to my host system. i need to stay on remote one. I tried with..
ssh user#remote logs.sh;bash -l
somehow it solves the problem but still not working exactly as a fresh login as the command:-
ssh user#remote
Or it will be better if i could include something in my script that would open the bash terminal in the same directory where the script was running. Please suggest.
Try this:
ssh -t user#remote 'logs.sh; bash -l'
The quotes are needed to pass both commands to ssh. The -t option forces a pseudo-tty allocation.
Discussion
Consider:
ssh user#remote logs.sh;bash -l
When the shell parses this line, it splits it into two commands. The first is:
ssh user#remote logs.sh
This runs logs.sh on the remote machine. The second command is:
bash -l
This opens a login shell on the local machine.
The quotes were added above to prevent the shell from splitting up the commands this way.

How can I ssh directly to a particular directory?

I often have to login to one of several servers and go to one of several directories on those machines. Currently I do something of this sort:
localhost ~]$ ssh somehost
Welcome to somehost!
somehost ~]$ cd /some/directory/somewhere/named/Foo
somehost Foo]$
I have scripts that can determine which host and which directory I need to get into but I cannot figure out a way to do this:
localhost ~]$ go_to_dir Foo
Welcome to somehost!
somehost Foo]$
Is there an easy, clever or any way to do this?
You can do the following:
ssh -t xxx.xxx.xxx.xxx "cd /directory_wanted ; bash --login"
This way, you will get a login shell right on the directory_wanted.
Explanation
-t Force pseudo-terminal allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services.
Multiple -t options force tty allocation, even if ssh has no local tty.
If you don't use -t then no prompt will appear.
If you don't add ; bash then the connection will get closed and return control to your local machine
If you don't add bash --login then it will not use your configs because its not a login shell
You could add
cd /some/directory/somewhere/named/Foo
to your .bashrc file (or .profile or whatever you call it) at the other host. That way, no matter what you do or where you ssh from, whenever you log onto that server, it will cd to the proper directory for you, and all you have to do is use ssh like normal.
Of curse, rogeriopvl's solution works too, but it's a tad bit more verbose, and you have to remember to do it every time (unless you make an alias) so it seems a bit less "fun".
My preferred approach is using the SSH config file (described below), but there are a few possible solutions depending on your usages.
Command Line Arguments
I think the best answer for this approach is christianbundy's reply to the accepted answer:
ssh -t example.com "cd /foo/bar; exec \$SHELL -l"
Using double quotes will allow you to use variables from your local machine, unless they are escaped (as $SHELL is here). Alternatively, you can use single quotes, and all of the variables you use will be the ones from the target machine:
ssh -t example.com 'cd /foo/bar; exec $SHELL -l'
Bash Function
You can simplify the command by wrapping it in a bash function. Let's say you just want to type this:
sshcd example.com /foo/bar
You can make this work by adding this to your ~/.bashrc:
sshcd () { ssh -t "$1" "cd \"$2\"; exec \$SHELL -l"; }
If you are using a variable that exists on the remote machine for the directory, be sure to escape it or put it in single quotes. For example, this will cd to the directory that is stored in the JBOSS_HOME variable on the remote machine:
sshcd example.com \$JBOSS_HOME
SSH Config File
If you'd like to see this behavior all the time for specific (or any) hosts with the normal ssh command without having to use extra command line arguments, you can set the RequestTTY and RemoteCommand options in your ssh config file.
For example, I'd like to type only this command:
ssh qaapps18
but want it to always behave like this command:
ssh -t qaapps18 'cd $JBOSS_HOME; exec $SHELL'
So I added this to my ~/.ssh/config file:
Host *apps*
RequestTTY yes
RemoteCommand cd $JBOSS_HOME; exec $SHELL
Now this rule applies to any host with "apps" in its hostname.
For more information, see http://man7.org/linux/man-pages/man5/ssh_config.5.html
I've created a tool to SSH and CD into a server consecutively – aptly named sshcd. For the example you've given, you'd simply use:
sshcd somehost:/some/directory/somewhere/named/Foo
Let me know if you have any questions or problems!
Based on additions to #rogeriopvl's answer, I suggest the following:
ssh -t xxx.xxx.xxx.xxx "cd /directory_wanted && bash"
Chaining commands by && will make the next command run only when the previous one was successful (as opposed to using ;, which executes commands sequentially). This is particularly useful when needing to cd to a directory performing the command.
Imagine doing the following:
/home/me$ cd /usr/share/teminal; rm -R *
The directory teminal doesn't exist, which causes you to stay in the home directory and remove all the files in there with the following command.
If you use &&:
/home/me$ cd /usr/share/teminal && rm -R *
The command will fail after not finding the directory.
In my very specific case, I just wanted to execute a command in a remote host, inside a specific directory from a Jenkins slave machine:
ssh myuser#mydomain
cd /home/myuser/somedir
./commandThatMustBeRunInside_somedir
exit
But my machine couldn't perform the ssh (it couldn't allocate a pseudo-tty I suppose) and kept me giving the following error:
Pseudo-terminal will not be allocated because stdin is not a terminal
I could get around this issue passing "cd to dir + my command" as a parameter of the ssh command (to not have to allocate a Pseudo-terminal) and by passing the option -T to explicitly tell to the ssh command that I didn't need pseudo-terminal allocation.
ssh -T myuser#mydomain "cd /home/myuser/somedir; ./commandThatMustBeRunInside_somedir"
I use the environment variable CDPATH
going one step further with the -t idea. I keep a set of scripts calling the one below to go to specific places in my frequently visited hosts. I keep them all in ~/bin and keep that directory in my path.
#!/bin/bash
# does ssh session switching to particular directory
# $1, hostname from config file
# $2, directory to move to after login
# can save this as say 'con' then
# make another script calling this one, e.g.
# con myhost repos/i2c
ssh -t $1 "cd $2; exec \$SHELL --login"
My answer may differ from what you really want, but I write here as may be useful for some people. In my solution you have to enter into the directory once and then every new ssh session goes to the same dir (after the first logout).
How to ssh to the same directory you have been in your last login.
(I assume you use bash on the remote node.)
Add this line to your ~/.bash_logout on the remote node(!):
echo $PWD > ~/.bash_lastpwd
and these lines to the ~/.bashrc file (still on the remote node!)
if [ -f ~/.bash_lastpwd ]; then
cd $(cat ~/.bash_lastpwd)
fi
This way you save your current path on every logout and .bashrc put you into that directory after login.
ps: You can tweak it further like using the SSH_CLIENT variable to decide to go into that directory or not, so you can differentiate between local logins and ssh or even between different ssh clients.
Another way of going to directly after logging in is create "Alias". When you login into your system just type that alias and you will be in that directory.
Example : Alias = myfolder '/var/www/Folder'
After you log in to your system type that alias (this works from any part of the system)
this command if not in bashrc will work for current session. So you can also add this alias to bashrc to use that in future
$ myfolder => takes you to that folder
I know this has been answered ages ago but I found the question while trying to incorporate an ssh login in a bash script and once logged in run a few commands and log back out and continue with the bash script. The simplest way I found which hasnt been mentioned elsewhere because it is so trivial is to do this.
#!/bin/bash
sshpass -p "password" ssh user#server 'cd /path/to/dir;somecommand;someothercommand;exit;'
Connect With User
In case if you don't know this, you can use this to connect by specifying both user and host
ssh -t <user>#<Host domain / IP> "cd /path/to/directory; bash --login"
Example: ssh -t admin#test.com "cd public_html; bash --login"
You can also append the commands to be executed on every login by appending it in the double quotes with a ; before each command
Unfortunately, the suggested solution (of #rogeriopvl) doesn't work when you use multiple hops, so I found another one.
On remote machine add into ~/.bashrc the following:
[ "x$CDTO" != "x" ] && cd $CDTO
This allows you to specify the desired target directory on command line in this way:
ssh -t host1 ssh -t host2 "CDTO=/desired_directory exec bash --login"
Sure, this way can be used for a single hop too.
This solution can be combined with the usefull tip of #redseven for greater flexibilty (if no $CDTO, go to saved directory, if exists).
SSH itself provides a means of communication, it does not know anything about directories. Since you can specify which remote command to execute (this is - by default - your shell), I'd start there.
simply modify your home with the command:
usermod -d /newhome username

Resources