See processes from given user on all machines - linux

On a linux server with different computers: is there a way to see all processes running from a given user on all machines?

Maybe it's too late for the answer, but for the records...
You can get it in this way:
hosts='192.168.1.x 192.168.1.y' # your hosts here
for host in $hosts; do
echo $host:
ssh some_user#$host 'ps -u given_user' # some_user for ssh, given_user for ps
done
In this way, you're creating an ssh session for each host:
ssh ... [user#]hostname [command]
If command is specified, command is executed on the remote host instead
of a login shell.
...and executing ps with the -u option:
-u userlist
Select by effective user ID (EUID) or name.
This selects the processes whose effective user name or ID is in userlist.

Related

How can i run bash on a remote linux server

Lets say i have two servers on the same network:
db-test-1
db-test-2
On db-test-1, how can i run a bash command that executes on db-test-2? For example, on db-test-1, run a command that checks if a program is running on the remote server, e.g,
ps -ef |grep consul
I have to use the server name, not IP by the way.
With ssh keys:
On db-test1: generate a pair of ssh keys (ssh-keygen)
Append or copy .ssh/id_rsa.pub of db-test1 to .ssh/authorized_keys
on db-test1: ssh db-test2 ps -ef | grep consul
The first connection you will be ask if you trust the remote host. You can remote this by adding: StrictHostKeyChecking no in .ssh/config

SSH to Remote Server Bash Programming

I programmed a script which SSH to remote server and get status of GPU server by executing following "nvidia-smi", well that was just a description and purpose of script, but the question is I run this as "root" which can ssh to another server passwordless but users can not, how can I program the script to let user to run the script and get status? of course without entering password to remote server, any authentication can I use?
Here is the script:
#!/bin/bash
HOSTS="gpuserver01\ngpuserver02"
SCRIPTS="nvidia-smi"
echo -e "which GPU server do you want to check?\n$HOSTS\n"-----------------""
echo "Please Enter Numebr of GPU Server"
read ans
#for HOSTNAME in $ans ; do
if [ $ans = '1' ]; then
HOSTNAME="gpuserver01"
ssh ${HOSTNAME} "${SCRIPTS}"
else
HOSTNAME="gpuserver02"
ssh ${HOSTNAME} "${SCRIPTS}"
fi
#done
Thank you.
You can give permissions to your script for other users to run as root privileges.
run visudo, add below;
Cmnd_Alias CUSTOM_CMD=/path/to/script/myscript.sh
myUser1 ALL = (root) NOPASSWD:CUSTOM_CMD
if other users have same group.Let say otherUsers
Cmnd_Alias CUSTOM_CMD=/path/to/script/myscript.sh
%otherUsers ALL = (root) NOPASSWD:CUSTOM_CMD
Add normal user to remote host (example gpuuser01).
Create SSH keys for that user. [1] Then check, you can log in to gpuuser01 without password.
Create new script on remote host (eg. gpuserver01), with setuid flag [2], that will run nvidia-smi.
Now you can connect to remote host and execute your script as root wihout password.
Rewrite your script (that one from question).
[1] https://kb.iu.edu/d/aews
[2] http://www.cyberciti.biz/faq/unix-bsd-linux-setuid-file/

Is it possible to get list of system in which my userid is login

I am working in a network having hundreds of servers , I want to know on which server my user id has been logging through terminal .
Is there any linux command exist for this ?
If you have ssh access to all theses machines, try:
for server in `cat serverlist.txt`; do ssh -q -o "BatchMode yes" $server "echo `hostname`" >> serverreport.txt; done
where you replace <username> with the user.
[depending of the implementation of last you may have to adapt parameters for head/tail]
(command adopted using last <username> from Analyzing UID/GID conflicts)

write a shell script to ssh to a remote machine and execute commands

I have two questions:
There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine. (Including some sudo operations). How can this be done using shell scripting?
When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.
The remote machines are VMs created on the run and I just have their IPs. So, I cant place a script file beforehand in those machines and execute them from my machine.
There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine. (Including some sudo operations). How can this be done using shell scripting?
You can do this with ssh, for example:
#!/bin/bash
USERNAME=someUser
HOSTS="host1 host2 host3"
SCRIPT="pwd; ls"
for HOSTNAME in ${HOSTS} ; do
ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
done
When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.
You can add the StrictHostKeyChecking=no option to ssh:
ssh -o StrictHostKeyChecking=no -l username hostname "pwd; ls"
This will disable the host key check and automatically add the host key to the list of known hosts. If you do not want to have the host added to the known hosts file, add the option -o UserKnownHostsFile=/dev/null.
Note that this disables certain security checks, for example protection against man-in-the-middle attack. It should therefore not be applied in a security sensitive environment.
Install sshpass using, apt-get install sshpass then edit the script and put your linux machines IPs, usernames and password in respective order. After that run that script. Thats it ! This script will install VLC in all systems.
#!/bin/bash
SCRIPT="cd Desktop; pwd; echo -e 'PASSWORD' | sudo -S apt-get install vlc"
HOSTS=("192.168.1.121" "192.168.1.122" "192.168.1.123")
USERNAMES=("username1" "username2" "username3")
PASSWORDS=("password1" "password2" "password3")
for i in ${!HOSTS[*]} ; do
echo ${HOSTS[i]}
SCR=${SCRIPT/PASSWORD/${PASSWORDS[i]}}
sshpass -p ${PASSWORDS[i]} ssh -l ${USERNAMES[i]} ${HOSTS[i]} "${SCR}"
done
This work for me.
Syntax : ssh -i pemfile.pem user_name#ip_address 'command_1 ; command 2; command 3'
#! /bin/bash
echo "########### connecting to server and run commands in sequence ###########"
ssh -i ~/.ssh/ec2_instance.pem ubuntu#ip_address 'touch a.txt; touch b.txt; sudo systemctl status tomcat.service'
There are a number of ways to handle this.
My favorite way is to install http://pamsshagentauth.sourceforge.net/ on the remote systems and also your own public key. (Figure out a way to get these installed on the VM, somehow you got an entire Unix system installed, what's a couple more files?)
With your ssh agent forwarded, you can now log in to every system without a password.
And even better, that pam module will authenticate for sudo with your ssh key pair so you can run with root (or any other user's) rights as needed.
You don't need to worry about the host key interaction. If the input is not a terminal then ssh will just limit your ability to forward agents and authenticate with passwords.
You should also look into packages like Capistrano. Definitely look around that site; it has an introduction to remote scripting.
Individual script lines might look something like this:
ssh remote-system-name command arguments ... # so, for exmaple,
ssh target.mycorp.net sudo puppet apply
The accepted answer sshes to machines sequentially. In case you want to ssh to multiple machines and run some long-running commands like scp concurrently on them, run the ssh command as a background process.
#!/bin/bash
username="user"
servers=("srv-001" "srv-002" "srv-002" "srv-003");
script="pwd;"
for s in "${servers[#]}"; do
echo "sshing ${username}#${s} to run ${script}"
(ssh ${username}#${s} ${script})& # Run in background
done
wait # If removed, you can run some other script here
If you are able to write Perl code, then you should consider using Net::OpenSSH::Parallel.
You would be able to describe the actions that have to be run in every host in a declarative manner and the module will take care of all the scary details. Running commands through sudo is also supported.
For this kind of tasks, I repeatedly use Ansible which allows to duplicate coherently bash scripts in several containets or VM. Ansible (more precisely Red Hat) now has an additional web interface AWX which is the open-source edition of their commercial Tower.
Ansible: https://www.ansible.com/
AWX:https://github.com/ansible/awx
Ansible Tower: commercial product, you will probably fist explore the free open-source AWX, rather than the 15days free-trail of Tower
There is are multiple ways to execute the commands or script in the multiple remote Linux machines.
One simple & easiest way is via pssh (parallel ssh program)
pssh: is a program for executing ssh in parallel on a number of hosts. It provides features such as sending input to all of the processes, passing a password to ssh, saving the output to files, and timing out.
Example & Usage:
Connect to host1 and host2, and print "hello, world" from each:
pssh -i -H "host1 host2" echo "hello, world"
Run commands via a script on multiple servers:
pssh -h hosts.txt -P -I<./commands.sh
Usage & run a command without checking or saving host keys:
pssh -h hostname_ip.txt -x '-q -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey -o PubkeyAuthentication=yes' -i 'uptime; hostname -f'
If the file hosts.txt has a large number of entries, say 100, then the parallelism option may also be set to 100 to ensure that the commands are run concurrently:
pssh -i -h hosts.txt -p 100 -t 0 sleep 10000
Options:
-I: Read input and sends to each ssh process.
-P: Tells pssh to display output as it arrives.
-h: Reads the host's file.
-H : [user#]host[:port] for single-host.
-i: Display standard output and standard error as each host completes
-x args: Passes extra SSH command-line arguments
-o option: Can be used to give options in the format used in the configuration file.(/etc/ssh/ssh_config) (~/.ssh/config)
-p parallelism: Use the given number as the maximum number of concurrent connections
-q Quiet mode: Causes most warning and diagnostic messages to be suppressed.
-t: Make connections time out after the given number of seconds. 0 means pssh will not timeout any connections
When ssh'ing to the remote machine, how to handle when it prompts for
RSA fingerprint authentication.
Disable the StrictHostKeyChecking to handle the RSA authentication prompt.
-o StrictHostKeyChecking=no
Source: man pssh
This worked for me. I made a function. Put this in your shell script:
sshcmd(){
ssh $1#$2 $3
}
sshcmd USER HOST COMMAND
If you have multiple machines that you want to do the same command on you would repeat that line with a semi colon. For example, if you have two machines you would do this:
sshcmd USER HOST COMMAND ; sshcmd USER HOST COMMAND
Replace USER with the user of the computer. Replace HOST with the name of the computer. Replace COMMAND with the command you want to do on the computer.
Hope this helps!
You can follow this approach :
Connect to remote machine using Expect Script. If your machine doesn't support expect you can download the same. Writing Expect script is very easy (google to get help on this)
Put all the action which needs to be performed on remote server in a shell script.
Invoke remote shell script from expect script once login is successful.

Trouble executing ssh IPAddressA -l user "ssh -l IPAddressB ls" from my bash script

I'm currently facing a weird problem while executing a command from my bash script.
My script has this command,
ssh IPAddressA -l root "ssh -l root IPAddressB ls"
where IPAddressA & IPAddressB would be replaced by hard coded IP addresses of two machines accessible from each other.
The user would enter the password whenever asked. But, I'm getting this error after I enter the IPAddressA's password.
root#IPAddressA's password:
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
]$
There's a better trick for that..
In ~/.ssh/config add a host entry for IPAddressA, configured like so:
Host IPAddressA
User someguy
ProxyCommand ssh -q someguy#IPAddressB nc -q0 %h 22
The slick thing about this method is that you can scp/sftp to IPAddressB without any weird stuff on your shell command line.
For bonus points, generate yourself a public key-pair and drop the public key on both IPAddressA and IPAddressB in ~/.ssh/authorized_keys. If you don't put a password on it, you won't even be bothered to enter that.
Additionally, if you're trying to get access to a remote LAN that only has a single entry point - SSH can actually act as a VPN client, bridging you through the proxy host. Of course, the remote end needs to support tap/tun devices (as does your local machine)... But if it's all there already.. super painless mechanism to bridge.
When the inner ssh password is prompted, there's no interactive keyboard available. You can get what you want with ssh tunneling.
ssh root#IPAddressA -L2222:IPAddressB:22 -Nf
ssh root#localhost -p2222
The first line open a tunnel, so your localhost 2222 port points to IPAddressB:22 andd bring the ssh process in background (-f) without executing a command (-N)
The second line connects IPAddressB:22 through the new opened tunnel

Resources