41

I find myself needing to log into various servers, set environment variables, and then work interactively.

e.g.

$ ssh anvil
jla@anvil$ export V=hello
jla@anvil$ export W=world
jla@anvil$ echo $V $W
hello world

How can I combine the first few commands, and then leave myself at a prompt?

Something like:

$ ssh anvil --on-login 'export V=hello; export W=world;'
jla@anvil$ echo $V $W
hello world

Obviously this is a model problem. What I am really asking is 'how do I ssh to a different machine, run some commands, and then continue as if I'd run them by hand?'

John Lawrence Aspden
  • 17,124
  • 11
  • 67
  • 110

5 Answers5

35

Probably the simplest thing is:

$ ssh -t host 'cmd1; cmd2; sh -i'

If you want to set variables, do:

$ ssh -t host 'cmd1; cmd2; FOO=hello sh -i'

Note that this is a terrible hack, and you would be much better off putting your desired initial commands in a script and doing:

$ scp setup host:~
$ ssh host
host$ . setup
William Pursell
  • 204,365
  • 48
  • 270
  • 300
18

You could also use the following expect script:

#!/usr/bin/expect -f
spawn ssh $argv
send "export V=hello\n"
send "export W=world\n"
send "echo \$V \$W\n"
interact
jcollado
  • 39,419
  • 8
  • 102
  • 133
  • This is super. I would rather have had something that could fit on a command line (and so appear in history, notes, etc). But I can make this work for what I want. Thanks! – John Lawrence Aspden Feb 15 '12 at 22:26
  • This wont work unless you have ssh keys setup for identity (private key) public key authentication. Otherwise ssh will prompt you for login credentials and you'd have to add them to your expect script, which can be a security issue since your saving your password in a file. Using expect is an interesting option tho. I can't use it because we have RSA token authentication - which means my password is a new random number generated every 30sec. – brookbot Jun 30 '22 at 18:01
4

Turns out this is answered by this question:

How can I ssh directly to a particular directory?

to ssh:

ssh -t anvil "export V=hello; export W=world; bash"

followed by:

jla@anvil$ echo $V $W
hello world
Community
  • 1
  • 1
John Lawrence Aspden
  • 17,124
  • 11
  • 67
  • 110
3

It is worth to note that ssh -t can actually be used to connect to one host via another host.

So for example if you want to execute a command on anvil, but anvil is only accessible from host gateway (by firewall etc.), you can do like this:

ssh gateway -t 'ssh anvil -t "export V=hello; export W=world;bash -l";'

Exiting the anvil, will also log you out of gateway (if you want to stay on gatway after leaving anvil than just add another bash -l before closing the command.

walkeros
  • 4,736
  • 4
  • 35
  • 47
0

Another approach is to execute this beast (also gives me a colored shell):

ssh host -t "echo 'rm /tmp/initfile; source ~/.bashrc; cd foo/; git status' > /tmp/initfile; bash --init-file /tmp/initfile"

David Vielhuber
  • 3,253
  • 3
  • 29
  • 34