Tubostic
Tubostic

Reputation: 11

Execute a remote script on a local server in Linux using ssh

I have a script called "test" on a remote server's home folder that contains the following lines:

#!/bin/bash

tengbe=`ifconfig | grep -B1 192.168 | awk 'NR==1 { print $1 }' | sed 's/://g'`

Basically, it just stores the name of the interface of the local server into a variable once the script is called. When I ssh into the remote server to call the script, I get an error:

ssh remoteserver-IP './test'
./test: line 3: ifconfig: command not found

What might be wrong with my script? I have seen various answers that does not offer a solution to my issue.

Upvotes: 1

Views: 1711

Answers (1)

slim
slim

Reputation: 41203

Try:

$ ssh remotehost ifconfig
bash: ifconfig: command not found

ifconfig isn't in your PATH on the remote host. You can prove it with:

$ which ifconfig
/sbin/ifconfig
$ ssh remotehost 'echo $PATH'
(returns lots of dirs, none of which is /sbin)

To get around this either specify the full path to ifconfig:

$ ssh remotehost /sbin/ifconfig

... or configure $PATH before calling it:

$ ssh remotehost 'PATH=$PATH:/sbin ifconfig'

... or edit $HOME/.bashrc (or alternatives -- read about your shell's initialisation process) to add /sbin to $PATH all the time.

For security, in a script it's usually better to specify absolute paths, maybe via variables. So in your script:

#!/bin/bash
IFCONFIG=/sbin/ifconfig
tengbe=$(${IFCONFIG} | grep -B1 192.168 | awk 'NR==1 { print $1 }' | sed 's/://g')

Note, I've replaced your backticks with $() - this isn't required, but it's a good habit to adopt - What is the benefit of using $() instead of backticks in shell scripts?

Upvotes: 1

Related Questions