Executing db2 command through ssh - linux

trying to ssh to another system then perform db2 commands however using 'su db2admin -c' does not seem to work, although it works for normal system commands ..
#!/bin/bash
sshpass -p 'passw0rd' ssh root#server.com "su db2admin -c 'db2text start'"
this is the output ..
rob#laptop:~/Desktop$ ./script.sh
bash: db2text: command not found
Any ideas?

The PATH is not getting updated to the normal root users PATH. Either specify the full path to db2text or add a dash (-) before the username to reload the environment variables

I'll hazard a guess and say that root doesn't have any of the db2 stuff in hi path.
And since you're using su db2admin rather than su - db2admin db2admin inherits
root's environment. Try with that extra - thrown in.
That all said: why on earth aren't you connecting w/ passwordless keys as db2admin?

Another solution that worked ..
#!/bin/bash
sshpass -p 'passw0rd' ssh root#server.com "su db2admin -c '~/sqllib/bin/db2text start'"
But problem is db2 path may change, better to use Eric's answer.

Related

ssh sudo to a different user execute commands on remote Linux server

We have a password less authentication between the server for root user, I am trying to run the alias on remote server as below
#ssh remoteserver runuser -l wasadmin wasstart
But it is not working. Any suggestions or any other method to achieve it
Based on your comments as you need to sudo to wasadmin in order to run wasadmin, you can try this:
ssh remoteserver 'echo /path/to/wasadmin wasstart | sudo su - wasadmin'
For add an alias in linux you must run
alias youcommandname=‘command’
Notice:
This will work until you close or exit from current shell . To fix this issue just add this to you .bash_profile and run source .bash_profile
Also your profile file name depending on which shell you using . bash , zsh ,...

cd to directory and su to particular user on remote server in script

I have some tasks to do on a remote Ubuntu CLI-only server in our offices every 2 weeks. I usually type the commands one by one, but I am trying to find a way (write a script maybe?) to decrease the time I spend in repeating those first steps.
Here is what I do:
ssh my_username#my_local_server
# asks for my_username password
cd /path/to/particular/folder
su particular_user_on_local_server
# asks for particular_user_on_local_server password
And then I can do my tasks (run some Ruby script on Rails applications, copy/remove files, restart services, etc.)
I am trying to find a way to do this in a one-step script/command:
"ssh connect then cd to directory then su to this user"
I tried to use the following:
ssh username#server 'cd /some/path/to/folder ; su other_user'
# => does not keep my connection open to the server, just execute my `cd`
# and then tells me `su: must be run from terminal`
ssh username#server 'cd /some/path/to/folder ; bash ; su other_user'
# => keeps my connection open to the server but doesn't switch to user
# and I don't see the usual `username:~/current/folder` prefix in the CLI
Is there a way to open a terminal (keep connection) on a remote server via ssh and change directory + switch to particular in a automated way? (to make things harder, I'm using Yakuake)
You can force allocation of a pseudo-terminal with -t, change to the desired directory and then replace the shell with one where you are the desired user:
ssh -t username#server 'cd /some/path/to/folder && exec bash -c "su other_user"'
sudo -H keeps the current working directory, so you could do:
ssh -t login_user#host.com 'cd /path/to/dir/; sudo -H -u other_user bash'
The -t parameter of ssh is needed otherwise the second sudo won't be able to ask you for your password.

Piping different values into bash command [duplicate]

How can you make SSH read the password from stdin, which it doesn't do by default?
based on this post you can do:
Create a command which open a ssh session using SSH_ASKPASS (seek SSH_ASKPASS on man ssh)
$ cat > ssh_session <<EOF
export SSH_ASKPASS="/path/to/script_returning_pass"
setsid ssh "your_user"#"your_host"
EOF
NOTE: To avoid ssh to try to ask on tty we use setsid
Create a script which returns your password (note echo "echo)
$ echo "echo your_ssh_password" > /path/to/script_returning_pass
Make them executable
$ chmod +x ssh_session
$ chmod +x /path/to/script_returning_pass
try it
$ ./ssh_session
Keep in mind that ssh stands for secure shell, and if you store your user, host and password in plain text files you are misleading the tool an creating a possible security gap
You can use sshpass which is for example in the offical debian repositories. Example:
$ apt-get install sshpass
$ sshpass -p 'password' ssh username#server
You can't with most SSH clients. You can work around it with by using SSH API's, like Paramiko for Python. Be careful not to overrule all security policies.
Distilling this answer leaves a simple and generic script:
#!/bin/bash
[[ $1 =~ password: ]] && cat || SSH_ASKPASS="$0" DISPLAY=nothing:0 exec setsid "$#"
Save it as pass, do a chmod +x pass and then use it like this:
$ echo mypass | pass ssh user#host ...
If its first argument contains password: then it passes its input to its output (cat) otherwise it launches whatver was presented after setting itself as the SSH_ASKPASS program.
When ssh encounters both SSH_ASKPASS AND DISPLAY set, it will launch the program referred to by SSH_ASKPASS, passing it the prompt user#host's password:
An old post reviving...
I found this one while looking for a solution to the exact same problem, I found something and I hope someone will one day find it useful:
Install ssh-askpass program (apt-get, yum ...)
Set the SSH_ASKPASS variable (export SSH_ASKPASS=/usr/bin/ssh-askpass)
From a terminal open a new ssh connection without an undefined TERMINAL variable (setsid ssh user#host)
This looks simple enough to be secure but did not check yet (just using in a local secure context).
Here we are.
FreeBSD mailing list recommends the expect library.
If you need a programmatic ssh login, you really ought to be using public key logins, however -- obviously there are a lot fewer security holes this way as compared to using an external library to pass a password through stdin.
a better sshpass alternative is :
https://github.com/clarkwang/passh
I got problems with sshpass, if ssh server is not added to my known_hosts sshpass will not show me any message, passh do not have this problem.
I'm not sure the reason you need this functionality but it seems you can get this behavior with ssh-keygen.
It allows you to login to a server without using a password by having a private RSA key on your computer and a public RSA key on the server.
http://www.linuxproblem.org/art_9.html

Running Remote Root Scripts on Fedora

I'd like to automate root scripting actions on my remote Fedora server via SSH without having to install the scripts on the server. To do this, I'm trying to use Bash's inline script notation. This works fine in Ubuntu, but I'm getting strange errors on Fedora.
e.g.
#!/bin/bash
ssh -t myuser#myserver <<EOI
su -
ls /root
exit
exit
EOI
This gives me the output:
standard in must be a tty
ls: cannot open directory /root: Permission denied
I've also tried:
#!/bin/bash
ssh -t myuser#myserver <<EOI
sudo ls /root
exit
EOI
but this gives me:
sudo: no tty present and no askpass program specified
If I manually ssh in and run these commands, they run fine since myuser is in the sudoers file. I've Googled these errors and have tried some fixes, but nothing's worked so far. How do I resolve this?
Looks like you're being prompted for the password but have no way to enter it. Here's a few things that should help.
Try an extra -t option: ssh -tt myuser#myserver <<EOI
Also this is a handy trick to log on as root without the root password being enabled: sudo su -
As a last resort you can setup your user to sudo without a password using visudo. You might see some comments like these to help you out:
# Uncomment to allow members of group sudo to not need a password
# (Note that later entries override this, so you might need to move
# it further down)
# %sudo ALL=NOPASSWD: ALL

How to pass password to scp?

I know it is not recommended, but is it at all possible to pass the user's password to scp?
I'd like to copy a file via scp as part of a batch job and the receiving server does, of course, need a password and, no, I cannot easily change that to key-based authentication.
Use sshpass:
sshpass -p "password" scp -r user#example.com:/some/remote/path /some/local/path
or so the password does not show in the bash history
sshpass -f "/path/to/passwordfile" scp -r user#example.com:/some/remote/path /some/local/path
The above copies contents of path from the remote host to your local.
Install :
ubuntu/debian
apt install sshpass
centos/fedora
yum install sshpass
mac w/ macports
port install sshpass
mac w/ brew
brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb
just generate a ssh key like:
ssh-keygen -t rsa -C "your_email#youremail.com"
copy the content of ~/.ssh/id_rsa.pub
and lastly add it to the remote machines ~/.ssh/authorized_keys
make sure remote machine have the permissions 0700 for ~./ssh folder and 0600 for ~/.ssh/authorized_keys
If you are connecting to the server from Windows, the Putty version of scp ("pscp") lets you pass the password with the -pw parameter.
This is mentioned in the documentation here.
curl can be used as a alternative to scp to copy a file and it supports a password on the commandline.
curl --insecure --user username:password -T /path/to/sourcefile sftp://desthost/path/
You can script it with a tool like expect (there are handy bindings too, like Pexpect for Python).
You can use the 'expect' script on unix/terminal
For example create 'test.exp' :
#!/usr/bin/expect
spawn scp /usr/bin/file.txt root#<ServerLocation>:/home
set pass "Your_Password"
expect {
password: {send "$pass\r"; exp_continue}
}
run the script
expect test.exp
I hope that helps.
You may use ssh-copy-id to add ssh key:
$which ssh-copy-id #check whether it exists
If exists:
ssh-copy-id "user#remote-system"
Here is an example of how you do it with expect tool:
sub copyover {
$scp = Expect->spawn("/usr/bin/scp ${srcpath}/$file $who:${destpath}/$file");
$scp->expect(30,"ssword: ") || die "Never got password prompt from $dest:$!\n";
print $scp 'password' . "\n";
$scp->expect(30,"-re",'$\s') || die "Never got prompt from parent system:$!\n";
$scp->soft_close();
return;
}
Nobody mentioned it, but Putty scp (pscp) has a -pw option for password.
Documentation can be found here: https://the.earth.li/~sgtatham/putty/0.67/htmldoc/Chapter5.html#pscp
Once you set up ssh-keygen as explained above, you can do
scp -i ~/.ssh/id_rsa /local/path/to/file remote#ip.com:/path/in/remote/server/
If you want to lessen typing each time, you can modify your .bash_profile file and put
alias remote_scp='scp -i ~/.ssh/id_rsa /local/path/to/file remote#ip.com:/path/in/remote/server/
Then from your terminal do source ~/.bash_profile. Afterwards if you type remote_scp in your terminal it should run the scp command without password.
Here's a poor man's Linux/Python/Expect-like example based on this blog post: Upgrading simple shells to fully interactive
TTYs. I needed this for old machines where I can't install Expect or add modules to Python.
Code:
(
echo 'scp jmudd#mysite.com:./install.sh .'
sleep 5
echo 'scp-passwd'
sleep 5
echo 'exit'
) |
python -c 'import pty; pty.spawn("/usr/bin/bash")'
Output:
scp jmudd#mysite.com:install.sh .
bash-4.2$ scp jmudd#mysite.com:install.sh .
Password:
install.sh 100% 15KB 236.2KB/s 00:00
bash-4.2$ exit
exit
Make sure password authentication is enabled on the target server. If it runs Ubuntu, then open /etc/ssh/sshd_config on the server, find lines PasswordAuthentication=no and comment all them out (put # at the start of the line), save the file and run sudo systemctl restart ssh to apply the configuration. If there is no such line then you're done.
Add -o PreferredAuthentications="password" to your scp command, e.g.:
scp -o PreferredAuthentications="password" /path/to/file user#server:/destination/directory
make sure you have "expect" tool before, if not, do it
# apt-get install expect
create the a script file with following content. (# vi /root/scriptfile)
spawn scp /path_from/file_name user_name_here#to_host_name:/path_to
expect "password:"
send put_password_here\n;
interact
execute the script file with "expect" tool
# expect /root/scriptfile
copy files from one server to other server ( on scripts)
Install putty on ubuntu or other Linux machines. putty comes with pscp. we can copy files with pscp.
apt-get update
apt-get install putty
echo n | pscp -pw "Password#1234" -r user_name#source_server_IP:/copy_file_path/files /path_to_copy/files
For more options see pscp help.
Using SCP non interactively from Windows:
Install the community Edition of netcmdlets
Import Module
Use Send-PowerShellServerFile -AuthMode password -User MyUser -Password not-secure -Server YourServer -LocalFile C:\downloads\test.txt -RemoteFile C:\temp\test.txt for sending File with non-interactive password
In case if you observe a strict host key check error then use -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null options.
The complete example is as follows
sshpass -p "password" scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root#domain-name.com:/tmp/from/psoutput /tmp/to/psoutput
You can use below steps. This works for me!
Step1-
create a normal file suppose "fileWithScpPassword" which contains the ssh password for the destination server.
Step2- use sshpaas -f followed by password file name and then normal scp command.
sshpass -f "fileWithScpPassword" scp /filePathToUpload user#ip:/destinationPath/
One easy way I do this:
Use the same scp cmd as you use with ssh keys i.e
scp -C -i <path_to opens sshkey> <'local file_path'> user#<ip_address_VM>: <'remote file_path’>
for transferring file from local to remote
but instead of providing the correct <path_to_opensshkey>, use some garbage path. Due to wrong key path you will be asked for password instead and you can simply pass the password now to get the work done!
An alternative would be add the public half of the user's key to the authorized-keys file on the target system. On the system you are initiating the transfer from, you can run an ssh-agent daemon and add the private half of the key to the agent. The batch job can then be configured to use the agent to get the private key, rather than prompting for the key's password.
This should be do-able on either a UNIX/Linux system or on Windows platform using pageant and pscp.
All the solutions mentioned above can work only if you the app installed or you should have the admin rights to install except or sshpass.
I found this very useful link to simply start the scp in Background.
$ nohup scp file_to_copy user#server:/path/to/copy/the/file > nohup.out 2>&1
https://charmyin.github.io/scp/2014/10/07/run-scp-in-background/
I found this really helpful answer here.
rsync -r -v --progress -e ssh user#remote-system:/address/to/remote/file /home/user/
Not only you can pass there the password, but also it will show the progress bar when copying. Really awesome.

Resources