How do I write a bash script that
first: login in to Ubuntu virtual machine
second: open terminal in VM and pass command in it?
Is there any way to do so?
Thanks
I assume that you have open a terminal window and you can login on you VM via ssh.
Create a file ~/hello.sh with the next content:
#!/bin/bash
mkdir ~/testdir
cd ~/testdir
echo "Hello" > hello.txt
Next run the follow command
ssh user@host < hello.sh
You will be asked for password and the script will be run.
If you use certificate (recommended) change the command with
ssh -i path_to_sert user@host < hello.sh
Log via ssh and check what you have
cat ~/testdir/hello.txt
By your question it seems that you want to log in to Ubuntu via GUI, then open a window with a terminal in it and execute some commands there. I may have misunderstood your question though. Please let me know if that's the case.
That's not a practical way to do it, and normally we'd rather use ssh to connect directly to the VM using the terminal on your physical computer. This means you can execute commands on your VM, but the output will be sent to the terminal on your physical computer - they won't show up on the VM's GUI screen with a terminal window open.
For this to work you must know your VM's IP address and install sshd (sudo apt-get install openssh-server) on the VM, then in your physical computer's terminal, you can execute:
ssh [VM's ip address]
to simply log in to its shell, or
ssh [VM's ip address] command
to execute [command] on the VM. If [command] is a shell script, it needs to be a shell script on the VM. You can also execute commands directly, for example:
ssh 192.168.0.100 ls -la
ssh 192.168.0.100 ls -la
it is supposed to exit afterwards. To go to a directory, then execute a command you can use semicolon to separate commands, or && if you want to execute the next command only if the previous one was successful. It's important that you enclose the commands in double quotes though, otherwise the second command will be executed locally. For example: ssh 192.168.0.100 "cd some-dir; ls -la"
Oct 18, 2015 at 18:18
ssh 192.168.0.100 "cd some-useless-dir && rm -rf ."
. Obviously, you need to be careful with rm -rf .
, but it's just a worst case scenario example. That command would wipe your home directory should some-useless-dir
not exist had you used semicolon instead of &&. && is like saying "and if that went well, ...". The opposite is ||, which can be read "or if that didn't work, try ...".
Oct 18, 2015 at 18:20
ssh
just like connecting to any other computer.