4

I need to run a batch to login to server, get in sudo su - username and run specific commands.

I tried below code:

putty username@servername -pw password -m myshell.sh

myshell.sh:

#!/bin/sh
sudo su - username
cd to particular folder
then tail a file

i am getting in sudo, but after that the script stucks until i logout.

7
  • Instead if running every command as sudo (with the password), login as root and run all the commands without sudo. Commented Dec 7, 2014 at 6:31
  • 1
    @Alfasin: who says he has ROOT access ? Commented Dec 7, 2014 at 11:56
  • Unless there is a need to CD, it's better to TAIL the file, supplying the full path in the TAIL command. Suppose the directory does not exist, what error messages will you get on the screen ? He'll state the file is missing, but it may not be obviouse he looks for that in a another (wrong) directory. It's also possible a file exists in the wrong directory. Commented Dec 7, 2014 at 11:59
  • @tvCa you're hair-splitting: so connect as the user that has permissions Commented Dec 7, 2014 at 17:42
  • You said ROOT, now you say : any user. Commented Dec 7, 2014 at 18:09

2 Answers 2

7

You can use sh -c and then use semicolons between commands, I'd consider the solution suggested in the comments though, just have whole script run as sudo.

sudo sh -c "cd /tmp;pwd;cd /dev;pwd""
Sign up to request clarification or add additional context in comments.

2 Comments

sh -c prompts for password which i dont have. i use "sudo su - username" and does not asks for password, then i can execute my commands. But running the script with sudo prompts for password.
@SurajModi: Which password is it asking for? ------ sh -c should not ask for any password and sudo asks for your password depending on the arguments used and the configuration in /etc/sudoers.
2

updated my shell file with below command and it worked:

#!/bin/sh
sudo su - username << block
cd /; 
tail filename;
block

all the commands are to be written in block and separated by ";"

1 Comment

Much cleaner and safer way would be to tell sudo to run the command(s) directly as the user username instead of running su as root. Additionally you do not need to use cd, just specify the full path of the file. According to your example it would be: /filename. ------ Here is the preferred command: sudo -u username tail /filename. Unfortunately the possibility to use sudo this way could be disabled in /etc/sudoers. ------ Note: In the script you do not need to separate commands by ; when they are separated by newlines already.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.