Read hostname and write it to another script at specefic position? - hostname

I wanna make startup script that change 2 lines in another script at startup or maybe not another script but to modify current to do same.
Here my current script that i use for ftp mirror.
User name must me my hostname and that way i dont need to modify this script for every new device but only change hostname of my devices.
Can someone plz help me achieve this?
#!/bin/bash
login="username"
pass="pass.username"
host="10.10.10.12"
base_name="$(basename "$0")"
lock_file="/home/mit/$base_name.lock"
trap "rm -f $lock_file" SIGINT SIGTERM
if [ -e "$lock_file" ]
then
echo "$base_name is running already."
exit
else
touch "$lock_file"
lftp -u $login,$pass $host << EOF
mirror --exclude-glob lost+found/ -n -e --use-cache /music/ /music/
quit
EOF
rm -f "$lock_file"
trap - SIGINT SIGTERM
exit
fi

I find a solution for my problem.
Here script that work way i want.
#!/bin/bash
sitecode=`cat /etc/hostname`;
login="${sitecode}"
pass="pass.${sitecode}"
host="10.10.10.12"
base_name="$(basename "$0")"
lock_file="/home/mit/$base_name.lock"
trap "rm -f $lock_file" SIGINT SIGTERM
if [ -e "$lock_file" ]
then
echo "$base_name is running already."
exit
else
touch "$lock_file"
lftp -u $login,$pass $host << EOF
mirror --exclude-glob lost+found/ -n -e --use-cache /music/ /music/
quit
EOF
rm -f "$lock_file"
trap - SIGINT SIGTERM
exit
fi

Related

Running a script when connecting to server with ssh

I use the kitty terminal emulator, so when I connect to a new server, I (usually) need to ad the terminfo (at least, this way it seems to work). To do this I wrote a script. While I was at it, I added a bit of code to add a public key if the user wants it to.
Not really relevant for the question, but here is the code:
#!/bin/bash
host=$1
ip=$(echo $host | cut -d# -f2 | cut -d: -f1)
# Check if it is a unknown host
if [[ -z $(ssh-keygen -F $ip) ]]; then
# Check if there are any ssh-keys
if [ $(ls $HOME/.ssh/*.pub > /dev/null | wc -l) -ne 0 ]; then
keys=$(echo $( (cd $HOME/.ssh/ && ls *.pub) | sed "s/.pub//g" ))
ssh -q -o PubkeyAuthentication=yes -o PasswordAuthentication=no $host "ls > /dev/null 2>&1"
# Check if the server has one of the public keys
if [ $? -ne 0 ]; then
echo "Do you want to add a SSh key to the server?"
while true; do
read -p " Choose [$keys] or leave empty to skip: " key
if [[ -z $key ]]; then
break
elif [[ -e $HOME/.ssh/$key ]]; then
# Give the server a public key
ssh $host "mkdir -p ~/.ssh && chmod 700 ~/.ssh && echo \"$(cat $HOME/.ssh/$key.pub)\" >> ~/.ssh/authorized_keys"
break
else
echo "No key with the name \"$key\" found."
fi
done
fi
fi
# Copy terminfo to server
ssh -t $host "echo \"$(infocmp -x)\" > \"\$TERM.info\" && tic -x \"\$TERM.info\" && rm \$TERM.info"
fi
It is not the best code, but it seems to work. Tips are ofcourse welcome.
The problem is that I need to run this script every time I connect te a new remote server (or I need to keep track of which server is new, but that is even worse). Is there a way to run this script every time I connect to a server (the script checks if the ip is a known host).
Or is there an other way to do this? Adding the public keys is nice to have, but not very important.
I hope somone can help,
Thanks!
There is a trick to identify that you are using ssh to login on the target machine:
pgrep -af "sshd.*"$USER |wc -l
The above command will count the user's processes using sshd
You can add the above command in the target machine, to test if you are connected via ssh. Add the above command to your .profile or .bash_profile script in the target machine.
So that only if you login via ssh your script will run initiation script on the target machine when you login/connect.
Sample .bash_profile on target machine
#!/bin/bash
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
if [[ $(pgrep -af "sshd.*"$USER |wc -l) -gt 0 ]]; then
your_init_script
fi

cannot kill process in FreeBSD

I have a script in FreeBSD 10.1 release, it's purpose is to monitor another process and keep the process alive.
When I try to kill itself, it always fail.
I try killall [name | pid]; pkill -9 [name]; service watchtas stop, none of them work.
Below is my script, please advise the solution.
#!/bin/sh
. /etc/rc.subr
prog="Thin-Agent WatchDog"
TAS_BIN="/etc/supermicro/tas-freebsd.x86_64"
TAS_LOG="/etc/supermicro/tas_system_crush.log"
monitor=1
name="watchtas"
rcvar=${name}_enable
command=/etc/rc.d/{$name}
start_cmd="watchdog"
stop_cmd="stop_watching"
load_rc_config $name
recover_tas() {
$TAS_BIN -agent start-service
RETVAl=$?
return $RETVAL
}
stop_watching() {
monitor=0
}
watchdog() {
while [ $monitor == 1 ]
do
tas_count=`ps -x | grep tas-freebsd.x86_64 | grep -v grep | wc -l | sed 's/ *//g'`
if [ $tas_count -eq 0 ]; then
timestamp=`date`
echo "[$timestamp]TAS shutdown unexpectedly, restarting TAS now..." >> $TAS_LOG
echo $?
recover_tas
else
sleep 10
fi
done
}
run_rc_command "$1"
Your start-up script fails in a couple of respects. service watchtas start does not return to the command line because the daemon process does not detach. service watchtas stop does not work as required because the variable monitor is local to the executing script.
I would separate the start-up script and the watchdog code into separate files and use daemon(8) to monitor the watchdog.
The /usr/local/etc/rc.d start-up script would look like this:
#!/bin/sh
. /etc/rc.subr
name="watchtas"
rcvar=${name}_enable
pidfile="/var/run/${name}.pid"
command="/usr/sbin/daemon"
command_args="-c -f -P ${pidfile} -r /usr/local/sbin/${name}"
load_rc_config $name
run_rc_command "$1"
The /usr/local/sbin/watchtas watchdog code would look something like this:
#!/bin/sh
TAS_BIN="/etc/supermicro/tas-freebsd.x86_64"
TAS_LOG="/etc/supermicro/tas_system_crush.log"
recover_tas() {
$TAS_BIN -agent start-service
RETVAl=$?
return $RETVAL
}
while true
do
tas_count=`ps -x | grep tas-freebsd.x86_64 | grep -v grep | wc -l | sed 's/ *//g'`
if [ $tas_count -eq 0 ]; then
timestamp=`date`
echo "[$timestamp]TAS shutdown unexpectedly, restarting TAS now..." >> $TAS_LOG
echo $?
recover_tas
else
sleep 10
fi
done
It seems you have a daemon watching a daemon watching a daemon.

How can I send password safely to tmux?

The following is my code in create_tmux.zsh
#!/bin/zsh
SESSIONNAME=$1
echo $SESSIONNAME
tmux has-session -t $SESSIONNAME &> /dev/null
if [ $? != 0 ]
then
tmux new-session -d -s $SESSIONNAME -n emacs
tmux new-window -t $SESSIONNAME:1 -n a
tmux send-keys -t $SESSIONNAME:1 'ssh -Y a#bc.com;$2' C-m
fi
tmux attach -t $SESSIONNAME
It's simple if I run
create_tmux.zsh ab $%^^&av1#
But in this way, it not only shows in the terminal of my password but also recorded in history.
How can I solve this?
Thank you

shell script not working

I have a shell script to do the following things
sudo as a user (johnsmith) and perform few things
Exit from that user and check url status
If status is not equal to 1 , ssh to one more server and execute a
script.
But when I am running it, the lines inside 'ENDBASH' are not getting executed at all.
#!/bin/ksh
echo "Outside ENDBASH ${###*/}"
sudo -u johnssmith bash <<'ENDBASH'
echo "Inside ENDBASH ${###*/}"
#Obtaining the new version file
for file in "${###*/}"
do
if echo "$file" | grep -E "abc_cde_efg"; then
echo "Version found: $file"
else
echo "Version not found"
fi
done
exit
ENDBASH
urlArray=('http://server:port/servicename1/services/servicename1?wsdl' 'http://server:port/servicename2/services/servicename2?wsdl')
status=0
for url in "${urlArray[#]}"
do
result=`curl -s $url`
if (echo $result | grep '<?xml' >/dev/null 2>&1); then
service=$(echo $url | cut -d"/" -f4)
echo "$service is Running"
else
service=$(echo $url | cut -d"/" -f4)
echo "$service is not Running"
status=1
fi
done
if [ $status != 1 ] ; then
ssh -t username#hostname /home/dev_was/test1.sh
fi
You need to explicitly pass the arguments received by your script to the internal script:
sudo -u johnssmith bash -s "$#" <<'ENDBASH'

Host key verification failed [rsync: connection unexpectedly closed]

I'm stuck with a peculiar problem, where rsync command is not running when it is executed through crontab.
Below is the code :
#!/bin/sh -x
PATH=/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/mysql/bin:/opt/android-sdk-linux/tools:/opt/android-sdk-linux/platform-tools:~/usr/lib/jvm/jdk-6/bin
/bin/sh /etc/profile
MyUSER="root" # USERNAME
MyPASS="password" # PASSWORD
MyHOST="localhost" # Hostname
Password="" #Linux Password
MYSQL="$(which mysql)"
if [ -z "$MYSQL" ]; then
echo "Error: MYSQL not found"
exit 1
fi
MYSQLADMIN="$(which mysqladmin)"
if [ -z "$MYSQLADMIN" ]; then
echo "Error: MYSQLADMIN not found"
exit 1
fi
CHOWN="$(which chown)"
if [ -z "$CHOWN" ]; then
echo "Error: CHOWN not found"
exit 1
fi
CHMOD="$(which chmod)"
if [ -z "$CHMOD" ]; then
echo "Error: CHMOD not found"
exit 1
fi
GZIP="$(which gzip)"
if [ -z "$GZIP" ]; then
echo "Error: GZIP not found"
exit 1
fi
CP="$(which cp)"
if [ -z "$CP" ]; then
echo "Error: CP not found"
exit 1
fi
MV="$(which mv)"
if [ -z "$MV" ]; then
echo "Error: MV not found"
exit 1
fi
RM="$(which rm)"
if [ -z "$RM" ]; then
echo "Error: RM not found"
exit 1
fi
RSYNC="$(which rsync)"
if [ -z "$RSYNC" ]; then
echo "Error: RSYNC not found"
exit 1
fi
MYSQLBINLOG="$(which mysqlbinlog)"
if [ -z "$MYSQLBINLOG" ]; then
echo "Error: MYSQLBINLOG not found"
exit 1
fi
# Get data in dd-mm-yyyy format
NOW="$(date +"%d-%m-%Y-%T")"
DEST="/home/db-backup"
mkdir $DEST/Increment_backup.$NOW
LATEST=$DEST/Increment_backup.$NOW
$MYSQLADMIN -u$MyUSER -p$MyPASS flush-logs
newestlog=`ls -d /usr/local/mysql/data/mysql-bin.?????? | sed 's/^.*\.//' | sort -g | tail -n 1`
echo $newestlog
for file in `ls /usr/local/mysql/data/mysql-bin.??????`
do
if [ "/usr/local/mysql/data/mysql-bin.$newestlog" != "$file" ]; then
echo $file
echo $Password | sudo -S $CHMOD 0777 $file
#sudo $MYSQLBINLOG $file>$file.$NOW.sql
$CP "$file" $LATEST
#$RM "$file.$NOW.sql"
#$MV $file.sql.gz /$LATEST
fi
done
for file1 in `ls $LATEST/mysql-bin.??????`
do
$MYSQLBINLOG $file1>$file1.$NOW.sql
$GZIP -9 "$file1.$NOW.sql"
$RM "$file1"
done
$RSYNC -v -e ssh $LATEST abc#192.168.1.9:/home/rsync-backup/
#FILE=$LATEST/"mysql-bin.??????"
#$MYSQLBINLOG $FILE>$FILE.$NOW.sql
#$GZIP -f "$FILE.$NOW.sql"
pwd
Rsync happens when the code is run manually, but fails when it is run through crontab. Rest of the commands are working fine. From the logs I got this information:
Host key verification failed.^M
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code 255) at io.c(600) [sender=3.0.6]
This is basically due to the first time authentication issue for ssh. If you were to ensure that the host is added to known_hosts manually or have an expect for the prompt in your script, it should work.
The authenticity of host '[IP]:20022 ([IP]:22)' can't be established.
RSA key fingerprint is bc:87:52:cf:ac:3e:67:74:1b:e1:0b:e3:e2:06:d8:21.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[IP]:22' (RSA) to the list of known hosts
This kind of error is usually caused by differences in the environment. A good troubleshooting step is to run "env" at the start of the program and compare the cron and non-cron version.
You should also run the command as "sh -x" which will show you all the expansions which will help identify which variable is not being set properly.
This could be your HOME directory is encrypted.
If your user is logged, it works, but when it's a cron, even it's executing the same user it does not have access to your $HOME/.ssh directory