Running remote commands after vagrant ssh
Asked Answered
M

3

41

vagrant ssh -- EXTRA SSH ARGS is supposed to allow extra args to be passed to ssh.

vagrant ssh -- -t 'cd /var/www' should ssh into vagrant and change directory to /var/www, but doesn't. Instead it returns

ssh: Could not resolve hostname ls: nodename nor servname provided, or not known

What am I missing?

Microbicide answered 20/3, 2014 at 3:52 Comment(0)
U
99

This works for me:

vagrant ssh -- -t 'cd /var/www; /bin/bash'
Urgent answered 20/3, 2014 at 9:52 Comment(4)
Aha! Brilliant. Start up bash so it doesn't exit immediately. Thank you! You can also do vagrant ssh -c 'echo hello; /bin/bash'Ronnie
@Ronnie - it won't work for me with vagrant -c. But this answer works.Trattoria
@progonkpa See vagrantup.com/docs/cli/ssh.html for an explanation on the behaviour of --Imperious
"If a -- (two hyphens) are found on the command line, any arguments after this are passed directly into the ssh executable. This allows you to pass any arbitrary commands to do things such as reverse tunneling down into the ssh program." This is valid with bash in general, not just with VagrantNinetieth
R
21

To run a command to a vagrant box remotelly run:

vagrant ssh -c "COMMAND; COMMAND1"

If you need, try vagrant ssh --help

Relax answered 2/10, 2017 at 18:51 Comment(2)
This answer doesn't work in my case, which is executing vagrant ssh -c "bundle exec rake some_task". When the command includes exec, it seems fail, and Emyl's answer works fine.Glabrescent
This allows you to stay on your machine after the command is executed.Redeemable
M
0

Late to the party, but this is still turning up high in Google search results.

Here's another nice way of sending scripts to a remote using a HEREDOC.

If on a Windows host, you'd need to be using a bash emulator like Git Bash or CygWin.

Note the escaped dollar sign, to prevent variables from being interpreted locally.

vagrant ssh admin -- -t <<HEREDOC
currentLogin=\$(whoami)
echo "hello \${currentLogin}"
pwd
ls -alZ
HEREDOC

hello vagrant
/home/vagrant
drwx------. vagrant vagrant unconfined_u:object_r:user_home_dir_t:s0 .
drwxr-xr-x. root    root    system_u:object_r:home_root_t:s0 ..
-rw-------. vagrant vagrant unconfined_u:object_r:user_home_t:s0 .bash_history
-rw-r--r--. vagrant vagrant unconfined_u:object_r:user_home_t:s0 .bash_logout
-rw-r--r--. vagrant vagrant unconfined_u:object_r:user_home_t:s0 .bash_profile
-rw-r--r--. vagrant vagrant unconfined_u:object_r:user_home_t:s0 .bashrc
drwx------. vagrant vagrant system_u:object_r:ssh_home_t:s0  .ssh
Milda answered 10/6, 2022 at 8:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.