In Unix, how to display welcome message if user has logged in from a particular IP (or host)? - linux

I want to display one message if user XYZ has logged in from any IP (or host).

Check to see if you have environment variables such as SSH_CLIENT and SSH_CONNECTION set. If so, you can access these from scripts (perl, bash, etc...) to dynamically generate a welcome message. Below, is a simple perl script to extract the IP address from env var SSH_CLIENT and output a welcome message.
#!/usr/bin/env perl
use strict; use warnings;
my $ip = (split / /, $ENV{SSH_CLIENT})[0];
if ($ip eq 'xxx.xxx.xxx.xxx') {
print "Hello XXXX\n";
}
else {
print "Hello from unknown IP\n";
}
Then you need to execute this script at login time. You can do this by calling the script from the end of /etc/profile.

Also This can be done using shell script as
REMOTE_IP=`echo $SSH_CONNECTION | cut -f1 -d " "`
if [ $REMOTE_IP == 'XXX.XXX.XXX.X' ] ;
then echo "Hi XXX" ;
else echo "Hi, stranger...";
fi
And then run this script from /etc/profile

Related

Xterm: How can I direct input from one terminal tab to another?

As I am a beginner coder, I apologize in advance for improper terminology.
This is the main script which calls the script ping.sh in a new tab.
#!/bin/bash
echo "The script is running!"
rm ping.txt
echo "Enter your desired IP address:"
read ADDRESS
osascript -e 'tell application "System Events" to tell application "Terminal"
do script "./ping.sh"
end tell'
echo "The script has ended!"
exit 0;
So, as I said the script ping.sh is called now. It goes like this.
#!/bin/bash
echo "Welcome to the new tab!"
ping -c 3 $ADDRESS > ping.txt
exit 0
The problem I have is that the read input from the first tab isn't recognizable in the second tab. Is there a way to solve this? I am probably missing a linking constructor or something like that. Please help!
I have no idea what osascript is, or how it works, but it might be helpful to know that shell scripts can access command line arguments with the special variables $1, $2, $3, etc.
This means you can rewrite your ping.sh script like so:
#!/bin/bash
echo "Welcome to the new tab!"
ping -c 3 "$1" > ping.txt
exit 0
And then call it like so:
#!/bin/bash
echo "Enter your desired IP address:"
read ADDRESS
./ping.sh "$ADDRESS"
Otherwise, to make sure subsequent commands have access to the same environment variables, you have to export them. From help export:
export: export [-fn] [name[=value] ...] or export -p
Set export attribute for shell variables.
Marks each NAME for automatic export to the environment of subsequently
executed commands. If VALUE is supplied, assign VALUE before exporting.
To make your original ping.sh work you could do the following:
#!/bin/bash
echo "Enter your desired IP address:"
read ADDRESS
export ADDRESS
./ping.sh

Automate response with read and expect in bash

I want to automate the process when the user is prompted to enter his name, it should automatically write world.
#!/bin/bash
fullname=""
read -p "hello" fullname
/usr/bin/expect -c "expect hello {send world}"
echo $fullname
The code above still waits for user input to be entered. I want to get the behavior as below:
hello
world
Is it possible to achieve such behavior using expect? If yes, how?
EDIT: One would expect that send world would store its result in fullname variable. All the idea is to have fullname variable for later usage
The line read -p "hello" fullname is where your script pauses.
It will read the user input and assign it to fullname
The script below will achieve what you are asking for.
#!/bin/bash
fullname=$(echo hello | /usr/bin/expect -c "expect hello {send world}")
echo "hello " $fullname
expect reads from stdin so we can use echo to send the data to it.
Then the output of expect is assigned to fullname.
Here is a link to a tutorial you might find useful. Bash Prog Intro
Usually expect drives/automates other programs like ftp, telnet, ssh or bash even. Using bash to drive an expect script is possible but not typical. Here's an expect script that does what I think you want:
[plankton#localhost ~]$ cat hello.exp
#!/usr/bin/expect
log_user 0
spawn read -p hello fn
expect {
hello {
send "world\r"
expect {
world {
puts $expect_out(buffer)
}
}
}
}
[plankton#localhost ~]$ ./hello.exp
world
But as you can see its the long way round to just executing puts world.
In bash one could do this ...
$ read -p "hello" fullname <<EOT
> world
> EOT
$ echo $fullname
world
... but once again just the long way round for:
fullname=world
I don't see why you need expect at all. To meet your requirements, all you need to do is:
echo world | /path/to/your/script
That will store "world" in the "fullname" variable.

Perl set and get env in different bash script

I have created a perl script which invokes two bash script. First script will set a envirnomental variable and the second will echo the environmental variable. I have given the contents of the files bellow
# perlscript.pl
print `. setnameenv.sh`;
print `. getnameenv.sh`;
# setnameenv.sh
export my_msg='hello world!'
# getnameenv.sh
echo $my_msg
now when I run the perl script perl perlscript.pl I am expecting the 'hello world' to be printed on the screen but actually I don't see any output. I there any way to do this without modifying the bash scripts?
You can embed perl into bash script,
#!/bin/bash
. setnameenv.sh
exec perl -x "$0" "$#"
#!perl
# your script below
print `. getnameenv.sh`;
From perldoc
-x
-xdirectory
tells Perl that the program is embedded in a larger chunk of unrelated text, such as in a mail message. Leading garbage will be discarded until the first line that starts with #! and contains the string "perl". Any meaningful switches on that line will be applied.
You spawn a shell, execute some commands to change its environment, then exit the shell. You never used the environment variable you created before exiting the shell. If you want a perl to see it, you're going to have to launch Perl from that shell.
. setnameenv.sh ; perlscript.pl
If you can't change how perlscript.pl is launched, you have a couple of options, none of which are that friendly. One of the options is to bootstrap.
BEGIN {
if (!length($ENV{my_msg})) {
require String::ShellQuote;
my $cmd = join(' ; ',
'. setnameenv.sh',
String::ShellQuote::shell_quote($^X, $0, #ARGV),
);
exec($cmd)
or die $!;
}
}
This can now be done in Perl with the Env::Modify module.
use Env::Modify qw(source);
source("setnameenv.sh");
# env settings from setnameenv.sh are now available to Perl
# and to the following system call
print `. getenvname.sh`; # or source again, like source("getenvname.sh")
The child process can inherit the parent's environment but cannot make any changes. Similarly the parent cannot have access to the child's environment as well. Hence to catch environment of the child in parent the child should print the values as shown in the bellow code. The below code will set already existing environment variables as well, but this can be optimized
# perlscript.pl
my $env_val = `. setnameenv.sh; env`;
my #env_list = split "\n", $env_str;
foreach (#env_list)
{
/([\w_]+)=(.*)/;
$ENV{$1} = $2;
}
print `. getnameenv.sh`;
find the actual explanation in this SO answer
Variables are only exported for the child processes.
You cannot export variables back to the father process.
You'll need another way to transport variables back to the father or the brothers.
For example, here is a example where all exported variables are saved and read from a file :
#!/bin/dash
# setnameenv.sh
export my_msg='hello world!'
export > savedVariables.sh
and
#!/bin/dash
# getnameenv.sh
. ./savedVariables.sh
echo "$my_msg"
Note : this works with dash. bash generates one line he cannot read back.

Set local environmental variable within a bash script

I'm trying to set an environmental variable that will persist once the script has finished running. It can go away after I end an ssh session.
Sample bash script:
# User picks an option
1) export dogs = cool
2) export dogs = not_cool
Running the script as source script.sh doesn't work since it kicks me out of my shell when ran and also requires the interactive menu so it won't work. Basically I want the user to be able to pick an option to switch between environmental variables in their shell. Is that even possible?
Source:
#!/bin/bash
set -x
show_menu(){
NORMAL=`echo "\033[m"`
MENU=`echo "\033[36m"` #Blue
NUMBER=`echo "\033[33m"` #yellow
FGRED=`echo "\033[41m"`
RED_TEXT=`echo "\033[31m"`
ENTER_LINE=`echo "\033[33m"`
echo -e "${MENU}*********************************************${NORMAL}"
echo -e "${MENU}**${NUMBER} 1)${MENU} Option 1 ${NORMAL}"
echo -e "${MENU}**${NUMBER} 2)${MENU} Option 2 ${NORMAL}"
echo -e "${MENU}*********************************************${NORMAL}"
echo -e "${ENTER_LINE}Please enter a menu option and enter or ${RED_TEXT}enter to exit. ${NORMAL}"
read opt
}
function option_picked() {
COLOR='\033[01;31m' # bold red
RESET='\033[00;00m' # normal white
MESSAGE=${#:-"${RESET}Error: No message passed"}
echo -e "${COLOR}${MESSAGE}${RESET}"
}
clear
show_menu
while [ opt != '' ]
do
if [[ $opt = "" ]]; then
exit;
else
case $opt in
1) clear;
option_picked "Option 1";
export dogs=cool
show_menu;
;;
2) clear;
option_picked "Option 2";
export dogs=not_cool
show_menu;
;;
x)exit;
;;
\n)exit;
;;
*)clear;
option_picked "Pick an option from the menu";
show_menu;
;;
esac
fi
done
The problem here is that . ./script.sh or source ./script.sh cannot run an interactive menu style script like this one. No way that I'm aware of to set local environmental variables from a bash script like I am trying to do here.
Redirect your normal echo's for user interaction to stderr (>&2)
echo the value that you want to have in your parent's environment to stdout (>&1)
if you changed your script that way you can call it like:
ENV_VAR=$( /path/to/your_script arg1 arg2 arg3 arg_whatever )
and now you have "exported" a variable to the "parent"
Try running your script with "./myscript.sh" which will use the current shell without invoking the new shell (still i doubt the hash bang might invokes the new shell).
Have a look here
Can also be solved with ~/.bashrc. The required environments can added in this file. If you need new shell with your own environment, you invoke "bash" with "bash --rcfile ".

Echo text that is user-editable

Is it possible to output text to a shell window, via bash script, that is user-editable? I essentially want to pre-fill certain information and give the user the ability to edit it if it's wrong.
For instance, if I were to write in a script:
echo -n "Enter your name: Anthony"
while read user_input
do
# do stuff with $user_input
done
How can I allow the user to inline edit the word Anthony only (aka, don't allow backspacing past the A in Anthony), and how can I store the value into a variable once the RETURN key is pressed?
EDIT
I'm looking for something similar to the -i option of read (see answer posted here), but this is only available on bash 4+. Is there an alternative for bash 3?
I needed similar setup recently so what I did was
$ cat a.sh
function input {
python -c '
import sys,readline
readline.set_startup_hook(lambda: readline.insert_text(sys.argv[2]))
sys.stderr.write(raw_input(sys.argv[1]))
' "$#" 3>&1 1>&2 2>&3
}
A=$( input 'question: ' default )
echo "A='$A'"
$ ./a.sh
question: default
A='default'
Well, it's not actually bash, but it made the job done.

Resources