Linux remote run script

execute code in remote linux machine

You can connect through ssh passing a command as a parameter:

ssh user@remote.ip.address "~/myscript.sh" 

To connect without password, use ssh keys. To use keys, you have to generate a pair at your machine, with the command:

Then take the contents of the file ~/.ssh/id_rsa.pub (or id_dsa.pub if you use parameter -t dsa in ssh-keygen) and put in the file ~/.ssh/authorized_keys of the remote_machine. The .ssh dir must have permission 700.

i my script i have «sudo . «, i got an error: sudo: no tty present and no askpass program specified. Do you know what is the problem?

yes, sudo is asking your password but there is no way the password can be asked to you. use the command «visudo» as root to edit the sudo permissions and add a NOPASSWD to your user config, something like this: youruser ALL=(ALL) NOPASSWD: ALL

Most Linux distros include ssh-copy-id , which will handle all of the steps after ssh-keygen . Thus, no need to copy the public key or worry about file permissions.

thanks for the tip about visuo. But i run into another problem after that. In my script, i execute ant and in my ant build script, it has if statement in there, and ant doesn’t seems to load library correctly. It looks like what ever shell I log into my machine is very limited. Is there a way to make it load just like I normally log into my machine?

I don’t know, but maybe the -t ssh option have something to do with this. -t forces psudo-tty allocation.

Источник

SSH: Execute Remote Command or Script – Linux

This is quite a common task for Linux system administrators, when it is needed to execute some command or a local Bash script from a one Linux workstation or a server on another remote Linux machine over SSH.

In this article you will find the examples of how to execute a remote command, multiple commands or a Bash script over SSH between remote Linux hosts and get back the output (result).

This information will be especially useful for ones, who want to create a Bash script that will be hosted locally on a one Linux machine but would be executed remotely on the other hosts over SSH.

Cool Tip: Connect to a remote SSH server without typing a password! Configure a passwordless authentication! Only 3 easy steps! Read more →

SSH: Execute Remote Command

Execute a remote command on a host over SSH:

Examples

Get the uptime of the remote server:

SSH: Run Multiple Remote Commands

Much more often it is required to send multiple commands on a remote server, for example, to collect some data for inventory and get back the result.

Читайте также:  Linux home directory terminal

There are a lot of different ways of how it can be done, but i will show the most popular of them.

Run multiple command on a remote host over SSH:

$ ssh USER@HOST 'COMMAND1; COMMAND2; COMMAND3'
$ ssh USER@HOST 'COMMAND1 | COMMAND2 | COMMAND3'

Cool Tip: SSH login is too slow? This can be fixed easily! Get rid of delay during authentication! Read more →

Examples

Get the uptime and the disk usage:

$ ssh root@192.168.1.1 'uptime; df -h'

Get the memory usage and the load average:

$ ssh root@192.168.1.1 'free -m | cat /proc/loadavg'

Show the kernel version, number of CPUs and the total RAM:

SSH: Run Bash Script on Remote Server

The equally common situation, when there is some Bash script on a Linux machine and it needs to connect from it over SSH to another Linux machine and run this script there.

The idea is to connect to a remote Linux server over SSH, let the script do the required operations and return back to local, without need not to upload this script to a remote server.

Certainly this can be done and moreover quite easily.

Cool Tip: Want to ROCK? Start a GUI (graphical) application on a remote Linux workstation over SSH! Read more →

Example

Execute the local script.sh on the remote server:

23 Replies to “SSH: Execute Remote Command or Script – Linux”

Hi,
How about executing a command remotely and making sure that it will be killed once i kill my ssh session. or getting of PID of either SSH or the actual command on remote-node via a script.
Something like this I want to achieve:
Example: collecting pcap on remote addr and storing it locally.

$ ssh -t -f "tcpdump -w -" > /tmp/tcp.pcap
$ ssh ADDRESS 'echo "rootpass" | sudo -Sv && bash -s' < BASH_FILE

How do create a scrip to run commands on multiple remote machines?
When the first one gets executed, the response returned to STOUT, and the next one is not executed until I ^C the previous command.
I tried using ‘exit’ command and ‘&’ , neither is working.

Hello everyone,
I am new to linux and trying to learn it. I have task to complete “Get last 3 login details of list of linux machine with date and time.”
Is there any way to achive it? Thanks in advance

You should change these examples to use double quotes – I got tripped up putting variables in these single quotes and took me a while to realise bash treats it as a string…

como puedo hacer que solo me pida una vez la contraseña de mi servidor? hice mi escript y como realizo varias tareas me pide varias veces la contraseña

Can someone help me write a shell script to shutdown a Ubuntu computer?
I’m going to have it run on a Mac, so that it will ssh into the Ubuntu and shut it down. I need it to open Application “Terminal” then ssh name@123.45.67.89, then give it the password.
Then I need it to issue command “sudo poweroff”, and give it the password again.
I know how to do this manually by opening Mac’s Terminal. I just type in “ssh name@123.456.78.9, it asks for the password, I type it in, and it’s connected. Then I just type in “sudo poweroff” and it asks for the password again, I type it in, and bam, it shuts down the Ubunt computer.
The problem is, I need to automate this to do it at a specific time of day. On the Mac, there is what is called “Automator”, and you can set up ICalendar Events to run an “Automator Workflow” with a Shell Script. I just don’t know how to write the Shell Script to do what I can do manually? Any help is appreciated greatly!

Читайте также:  Arch linux network drivers

I solved this. Here’s what works:
tell application “Terminal”
activate
do script (“ssh test@192.168.1.10“)
delay 6
do script “password” in front window
delay 7
do script “sudo poweroff” in front window
delay 5
do script “password” in front window
end tell

Why when I get a script from somewhere by curl & then pipe to bash to run it on my local server, some commands in a bash functions failed to execute, no error, no code error btw..just the called functions don’t execute.. How do I know my code is ok, because when I output it as a file from curl, I chmod and run it like ./..scriptfile.sh.. Code run fine.. Any idea and how do I resolve this?

This was very helpful for me. I am very new to this and just ordered a VPS yesterday and these guides are really helping me work my way around. I appreciate this simple resource you’ve put together!

how to run a script with sudo previllages on remote server: ssh -tt rundeck@$Batch_Host ‘ bash -s’ < /home/abhishekc/dem.sh i am getting permission denied

Источник

Run scripts remotely via SSH

I need to collect user information from 100 remote servers. We have public/private key infrastructure for authentication, and I have configured ssh-agent command to forward key, meaning i can login on any server without password prompt (auto login). Now I want to run a script on all server to collect user information (how many user account we have on all servers). This is my script to collect user info.

#!/bin/bash _l="/etc/login.defs" _p="/etc/passwd" ## get mini UID limit ## l=$(grep "^UID_MIN" $_l) ## get max UID limit ## l1=$(grep "^UID_MAX" $_l) awk -F':' -v "min=$" -v "max=$" '< if ( $3 >= min && $3 ' "$_p" 

6 Answers 6

Since you need to log into the remote machine there is AFAICT no way to do this "without ssh". However, ssh accepts a command to execute on the remote machine once logged in (instead of the shell it would start). So if you can save your script on the remote machine, e.g. as ~/script.sh , you can execute it without starting an interactive shell with

$ ssh remote_machine ~/script.sh 

Once the script terminates the connection will automatically be closed (if you didn't configure that away purposely).

Читайте также:  Расшарить папку linux windows

Ah! how did i miss scp 🙁 I can do scp without password and push this script to /tmp directory of all remote server and run ssh to execute them.. thats for remind me.

If you're going to install things on each system anyway, why not go all the way and use a full-blown tool like Munin? You can add custom information to that, graph your results over time, set up notifications if hosts become unreachable. Monitoring is good. 🙂 There are instructions on installing Munin on Linux systems using yum within the Munin documentation.

Sounds like something you can do using expect.

Expect is a program that "talks" to other interactive programs according to a script. Following the script, Expect knows what can be expected from a program and what the correct response should be.

Cool. I know I have some Expect scripts I used for getting information out of multiple servers. As soon as I find them, I'll publish a sample here.

If you've got a key on each machine and can ssh remotehost from your monitoring host, you've got all that's required to collect the information you've asked for.

#!/bin/bash servers=(wopr gerty mother) fmt="%s\t%s\t%s\n" printf "$fmt" "Host" "UIDs" "Highest" printf "$fmt" "----" "----" "-------" count='awk "END " /etc/passwd' # avoids whitespace problems from `wc` highest="awk -F: '\$3>n&&\$3 END' /etc/passwd" for server in $; do printf "$fmt" "$server" "$(ssh "$server" "$count")" "$(ssh "$server" "$highest")" done 
$ ./doit.sh Host UIDs Highest ---- ---- ------- wopr 40 2020 gerty 37 9001 mother 32 534 

Note that this makes TWO ssh connections to each server to collect each datum. If you'd like to do this a little more efficiently, you can bundle the information into a single, slightly more complex collection script:

#!/usr/local/bin/bash servers=(wopr gerty mother) fmt="%s\t%s\t%s\n" printf "$fmt" "Host" "UIDs" "Highest" printf "$fmt" "----" "----" "-------" gather="awk -F: '\$3>n&&\$3 END' /etc/passwd" for server in $; do read count highest < <(ssh "$server" "$gather") printf "$fmt" "$server" "$count" "$highest" done 

ssh remoteserver.example /bin/bash < localscript.bash

(Note: the "proper" way to authenticate without manually entering in password is to use SSH keys. Storing password in plaintext even in your local scripts is a potential security vulnerability)

You can run expect as part of your bash script. Here's a quick example that you can hack into your existing script:

login=user IP=127.0.0.1 password='your_password' expect_sh=$(expect -c " spawn ssh $login@$IP expect \"password:\" send \"$password\r\" expect \"#\" send \"./$remote_side_script\r\" expect \"#\" send \"cd /lib\r\" expect \"#\" send \"cat file_name\r\" expect \"#\" send \"exit\r\" ") echo "$expect_sh" 

You can also use pscp to copy files back and forth as part of a script so you don't need to manually supply the password as part of the interaction:

$ sudo apt-get install putty-tools 

Using pscp in your script:

pscp -scp -pw $password file_to_copy $login@$IP:$dest_dir 

Источник

Оцените статью
Adblock
detector