Initializing an ssh session from cap 3? - ssh

I used to use cap-ssh for a shortcut to initiate an ssh connection to the server, but it doesn't look like it works in capistrano 3 anymore.
Does anyone have any suggestions for starting an ssh connection from capistrano in cap 3?

You can define ssh task like this:
desc 'Start an ssh session to your servers.'
task :ssh do
role = (ENV['ROLE'] || :app).to_sym
on roles(role) do
hosts = env.instance_variable_get(:#servers).instance_variable_get(:#servers)
hosts = hosts.select { |h| h.roles.include? role } if role
if hosts.size > 1
$stdout.puts "Pick a server to connect to:"
hosts.each.with_index do |host, i|
$stdout.puts "\t#{i + 1}: #{host.user}##{host.hostname} role: #{host.roles.to_a}"
end
selected = $stdin.gets
selected = 1 if selected.empty?
host = hosts[selected.to_i - 1]
else
host = hosts.first
end
fail "No server defined!" unless host
port = host.netssh_options[:port] || fetch(:ssh_options) && fetch(:ssh_options)[:port] || 22
system "ssh -t -p #{port} #{host.user}##{host.hostname} #{host.netssh_options[:forward_agent] ? '-a' : ''} 'cd #{current_path}; bash --login'"
end
end

Related

Gitlab-ci problems pushing to the private registry with HTTPS

I'm trying to push an image to my registry with the gitlab ci. I can login without any problems (the before script). However I get the following error on the push command. error parsing HTTP 400 response body: invalid character '<' looking for beginning of value: "<html>\r\n<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>\r\n<body>\r\n<center><h1>400 Bad Request</h1></center>\r\n<center>The plain HTTP request was sent to HTTPS port</center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n"
This in the config.toml from the used gitlab-runner
[[runners]]
name = "e736f9d48a40"
url = "https://gitlab.domain.com/"
token = "token"
executor = "docker"
[runners.custom_build_dir]
[runners.cache]
[runners.cache.s3]
[runners.cache.gcs]
[runners.cache.azure]
[runners.docker]
tls_verify = false
image = "docker"
privileged = true
disable_entrypoint_overwrite = false
oom_kill_disable = false
disable_cache = false
volumes = ["/cache"]
shm_size = 0
This is the relevant part of the gitlab-ci
image: docker
services:
- docker:dind
variables:
BACKEND_PROJECT: "test"
DOCKER_DRIVER: overlay2
DOCKER_TLS_CERTDIR: ""
containerize:
stage: containerize
before_script:
- "docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY"
only:
- master
script:
- "cd backend/"
- "docker build -t $CI_REGISTRY_IMAGE/api:latest ."
- "docker push $CI_REGISTRY_IMAGE/api:latest"
The GitLab omnibus registry configuration
registry_external_url 'https://gitlab.domain.com:5050'
registry_nginx['enable'] = true
registry_nginx['ssl_certificate_key'] = "/etc/letsencrypt/live/gitlab.domain.com/privkey.pem"
registry_nginx['ssl_certificate'] = "/etc/letsencrypt/live/gitlab.domain.com/fullchain.pem"
registry_nginx['port'] = 443
registry_nginx['redirect_http_to_https'] = true
### Settings used by Registry application
registry['enable'] = true
registry_nginx['proxy_set_headers'] = {
"Host" => "$http_host",
"X-Real-IP" => "$remote_addr",
"X-Forwarded-For" => "$proxy_add_x_forwarded_for",
"X-Forwarded-Proto" => "http",
"X-Forwarded-Ssl" => "on"
}
Can someone help me with this problem?
Okay, the solution was quite simple. I only had to change the
"X-Forwarded-Proto" => "http",
to
"X-Forwarded-Proto" => "https",

How to ask for a user input from a remote server with SSHKit?

I need to ask a user input from a ruby script on a remote server. I managed to perform it with bash with the following code
class ConfirmHandler
def on_data(command, stream_name, data, channel)
puts "data received: #{data}"
if data.to_s =~ /\?$/
prompt = Net::SSH::Prompt.default.start(type: 'confirm')
response = prompt.ask "Please enter your response (y/n)"
channel.send_data "#{response}\n"
end
end
end
require 'sshkit'
require 'sshkit/dsl'
include SSHKit::DSL
on '<ssh-server-name>' do |host|
cmd = <<-CMD
echo 'Do something?';
read response;
echo response=$response
CMD
capture(cmd.squish , interaction_handler: ConfirmHandler.new)
end
When I run this script on my local machine I see
data received: Do something?
Please enter your response (y/n)
data received: response=y
I try to wrap the bash CMD code into a ruby script:
on '<ssh-server-name>' do |host|
cmd = <<-CMD
ruby -e "
puts 'Do something?';
require 'open3';
response = Open3.capture3('read response; echo $response');
puts 'response=' + response.to_s;
"
CMD
capture(cmd.squish , interaction_handler: ConfirmHandler.new)
end
and get the following result:
data received: Do something?
Please enter your response (y/n)
data received: response=["\n", "", #<Process::Status: pid 9081 exit 0>]
I was writing the code above looking at the Interactive commands section on the SSHKit Github home page
How can I capture the user response from a ruby script with SSKKit on the remote server?
I was able to capture the user response from a ruby script on a remote server with the following code:
# ask_response.rb
puts 'Do something?';
response = `read response; echo $response`;
puts 'response=' + response.to_s;
ask_response.rb is a ruby script which is located on a remote server. And locally I run:
on '<ssh-server-name>' do |host|
capture("ruby ask_response.rb" , interaction_handler: ConfirmHandler.new)
end

vagrant up command times out after "SSH auth method: private key" line

I have installed Ubuntu 16.04 on in VirtualBox on Windows 8.1 operating system.
I boot my Virtual box with Ubuntu 16.04 and inside it, when I am trying to run vagrant up, it freezes at default: ssh auth method: private key line and finally times out after 600 seconds (which I set into Vagrantfile).
Timed out while waiting for the machine to boot. This means that
Vagrant was unable to communicate with the guest machine within
the configured ("config.vm.boot_timeout" value) time period. If you look above, you should be able to see the error(s) that Vagrant had when attempting to connect to the machine. These errors are usually good hints as to what may be wrong. If you're using a custom box, make sure that networking is properly working and you're able to connect to the machine. It is a common problem that networking isn't setup properly in these boxes. Verify that authentication configurations are also setup properly,
as well. If the box appears to be booting properly, you may want to increase the timeout ("config.vm.boot_timeout") value.
I am running vagrant up command from its location.
$ /var/www/yrc-2017$ vagrant up
My Vagrantfile looks like this:
if Gem::Version.new(Vagrant::VERSION) < Gem::Version.new("1.5.0")
puts "ERROR: Outdated version of Vagrant"
puts " Chassis requires Vagrant 1.5.0+ "
puts
exit 1
end
if not File.exist?(File.join(File.dirname(__FILE__), "puppet", "modules", "apt", ".git"))
puts "NOTICE: Submodules not found, updating for you"
if not system("git submodule update --init", :chdir => File.dirname(__FILE__))
puts "WARNING: Submodules may be missing, and could not automatically\ndownload them for you."
end
# Extra new line, please!
puts
end
require_relative "puppet/chassis.rb"
CONF = Chassis.config
Chassis.install_extensions(CONF)
base_path = Pathname.new( File.dirname( __FILE__ ) )
module_paths = [ base_path.to_s + "/puppet/modules" ]
module_paths.concat Dir.glob( base_path.to_s + "/extensions/*/modules" )
module_paths.map! do |path|
pathname = Pathname.new(path)
pathname.relative_path_from(base_path).to_s
end
Vagrant.configure("2") do |config|
# Set up potential providers.
config.vm.provider "virtualbox" do |vb|
# Use linked clones to preserve disk space.
vb.linked_clone = true if Vagrant::VERSION =~ /^1.8/
end
config.vm.box = "bento/ubuntu-16.04"
# Adding boot timeout
config.vm.boot_timeout = 600
# Enable SSH forwarding
config.ssh.forward_agent = true
# Disable updating of Virtual Box Guest Additions for faster provisioning.
if Vagrant.has_plugin?("vagrant-vbguest")
config.vbguest.auto_update = false
end
# Having access would be nice.
if CONF['ip'] == "dhcp"
config.vm.network :private_network, type: "dhcp", hostsupdater: "skip"
else
config.vm.network :private_network, ip: CONF['ip'], hostsupdater: "skip"
end
config.vm.hostname = CONF['hosts'][0]
config.vm.network "forwarded_port", guest: 22, host: 2222, host_ip: "127.0.0.1", id: 'ssh'
preprovision_args = [
CONF['apt_mirror'].to_s,
CONF['database']['has_custom_prefix'] ? "" : "check_prefix"
]
config.vm.provision :shell, :path => "puppet/preprovision.sh", :args => preprovision_args
config.vm.provision :puppet do |puppet|
puppet.manifests_path = "puppet/manifests"
puppet.manifest_file = "development.pp"
module_paths.map! { |rel_path| "/vagrant/" + rel_path }
puppet.options = "--modulepath " + module_paths.join( ':' ).inspect
puppet.options += " --hiera_config /dev/null"
puppet.options += " --disable_warnings=deprecations"
end
config.vm.provision :shell do |shell|
shell.path = "puppet/postprovision.sh"
shell.args = [
# 0 = hostname
CONF['hosts'][0],
# 1 = username
CONF['admin']['user'],
# 2 = password
CONF['admin']['password']
]
end
synced_folders = CONF["synced_folders"].clone
synced_folders["."] = "/vagrant"
mount_opts = CONF['nfs'] ? [] : ["dmode=777","fmode=777"]
synced_folders.each do |from, to|
config.vm.synced_folder from, to, :mount_options => mount_opts, :nfs => CONF['nfs']
if CONF['nfs'] && Vagrant.has_plugin?("vagrant-bindfs")
config.bindfs.bind_folder to, to
end
end
# Success?
end
I only added the following two lines in above file:
config.vm.boot_timeout = 600
Reference
and
config.vm.network "forwarded_port", guest: 22, host: 2222, host_ip: "127.0.0.1", id: 'ssh'
Reference
What should I do?
UPDATE
I have the following settings in VirtualBox > System on Windows 8.1
Paravitualization Interface: Default
Hardware Virtualization:
- Enable VT-x/AMD-V
- Enable Nested Paging
And all the options above are disabled, means I cannot change anything.
Screenshot:
Try and write "Vagrant ssh" after vagrant up, and if it asks for credentials it is "vagrant", if the issue is not fixed with a vagrant up --provision or a vagrant reload (halt and up), then delete your box and rebuild it from the box you started out with.
it have happen to me some times, when i try to upgrade the boxes i have, then i just have to re-setup the box and everything works.
it happens that the system does not gets the system propperly started.

Terraform cannot connect Chef provisioner with ssh

I cannot get terraform's ssh to connect via private aws keypair for chef provisioning - the error looks to just be a timeout:
aws_instance.app (chef): Connecting to remote host via SSH...
aws_instance.app (chef): Host: 96.175.120.236:32:
aws_instance.app (chef): User: ubuntu
aws_instance.app (chef): Password: false
aws_instance.app (chef): Private key: true
aws_instance.app (chef): SSH Agent: true
aws_instance.app: Still creating... (5m30s elapsed)
Error applying plan:
1 error(s) occurred:
* dial tcp 96.175.120.236:32: i/o timeout
Terraform does not automatically rollback in the face of errors.
Instead, your Terraform state file has been partially updated with
any resources that successfully completed. Please address the error
above and apply again to incrementally change your infrastructure.
Here is my terraform plan - note the ssh settings.. the key_name setting is set to my AWS keypair name and the ssh_for_chef.pem is the private key
variable "AWS_ACCESS_KEY" {}
variable "AWS_SECRET_KEY" {}
provider "aws" {
region = "us-east-1"
access_key = "${var.AWS_ACCESS_KEY}"
secret_key = "${var.AWS_SECRET_KEY}"
}
resource "aws_instance" "app" {
ami = "ami-88aa1ce0"
count = "1"
instance_type = "t1.micro"
key_name = "ssh_for_chef"
security_groups = ["sg-c43490e1"]
subnet_id = "subnet-75dd96e2"
associate_public_ip_address = true
provisioner "chef" {
server_url = "https://api.chef.io/organizations/xxxxxxx"
validation_client_name = "xxxxxxx-validator"
validation_key = "/home/user01/Documents/Devel/chef-repo/.chef/xxxxxxxx-validator.pem"
node_name = "dubba_u_7"
run_list = [ "motd_rhel" ]
user_name = "user01"
user_key = "/home/user01/Documents/Devel/chef-repo/.chef/user01.pem"
ssl_verify_mode = "false"
}
connection {
type = "ssh"
user = "ubuntu"
private_key = "${file("/home/user01/Documents/Devel/ssh_for_chef.pem")}"
}
}
Any ideas?
I'm not sure if we had the same problem, since you didn't specify if you were able to ssh to the instance.
In my case, I was running terraform from within the VPC, and the connection was allowed with a security groups, which can't be used with a public IP.
the solution is simple (but you will have to use the new conditional interpolations of terraform v.0.8.0) -
Define this variable - variable use_public_ip { default = true }
Then, inside the connection section of the chef provisioner, add the following line -
host = "${var.use_public_ip ? aws_instance.instance.public_ip : aws_instance.instance.private_ip}"
If you wish to use the public IP, set the variable as true, otherwise, set it to false.
I use this for aws -
connection {
user = "ubuntu"
host = "${var.use_public_ip ? aws_instance.instance.public_ip : aws_instance.instance.private_ip}","
}

Cisco VPN Client automatic login

I need to automate the login process of a Cisco VPN Client version 5.0.07.0440.
I've tried using a command line like this but there is something wrong:
vpnclient.exe connect MyVPNConnection user username pwd password
This starts the connection but then a User Authentication dialog is shown, asking for username, password and domain. Username and password are already filled, domain is not necessary.
To continue I must press the OK button.
Is there a way to not show the dialog and automatically login into the vpn?
Run vpnclient.exe /?:
That way just run
vpnclient.exe connect MyVPNConnection -s < file.txt
file.txt
username
password
Below worked for me Cisco AnyConnect Secure Mobility Client:
Try to connect to VPN for the first time using vpncli.exe and note every keystroke i.e every command, every enter( \n ) you press, username & password you enter.
Copy each command sequentially in .login_info file.
Sample .login_info:
connect unkbown.data-protect.com
\n
\n
KC23452
\n
Note: Replace \n with normal enter, these are the exact steps that I followed while connecting via vpncli.exe. Username and group-name were saved automatically that's the reason the 2nd and 3rd lines are \n ( enter ). Also, the last \n is required.
Go to C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client
Open CMD here
vpncli.exe -s < .login_info
First, we need to use the vpncli.exe command line approach with the -s switch.
It works from command line or script. If you were looking for a solution in C#:
//file = #"C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"
var file = vpnInfo.ExecutablePath;
var host = vpnInfo.Host;
var profile = vpnInfo.ProfileName;
var user = vpnInfo.User;
var pass = vpnInfo.Password;
var confirm = "y";
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = file,
Arguments = string.Format("-s"),
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
}
};
proc.OutputDataReceived += (s, a) => stdOut.AppendLine(a.Data);
proc.ErrorDataReceived += (s, a) => stdOut.AppendLine(a.Data);
//make sure it is not running, otherwise connection will fail
var procFilter = new HashSet<string>() { "vpnui", "vpncli" };
var existingProcs = Process.GetProcesses().Where(p => procFilter.Contains(p.ProcessName));
if (existingProcs.Any())
{
foreach (var p in existingProcs)
{
p.Kill();
}
}
proc.Start();
proc.BeginOutputReadLine();
//simulate profile file
var simProfile = string.Format("{1}{0}{2}{0}{3}{0}{4}{0}{5}{0}"
, Environment.NewLine
, string.Format("connect {0}", host)
, profile
, user
, pass
, confirm
);
proc.StandardInput.Write(simProfile);
proc.StandardInput.Flush();
//todo: these should be a configurable value
var waitTime = 500; //in ms
var maxWait = 10;
var count = 0;
var output = stdOut.ToString();
while (!output.Contains("state: Connected"))
{
output = stdOut.ToString();
if (count > maxWait)
throw new Exception("Unable to connect to VPN.");
count++;
Thread.Sleep(waitTime);
}
stdOut.Append("VPN connection established! ...");
(This might have extra stuff which is not required for you specific case.)
Here is a BAT script for automatic logon using Cisco AnyConnect Secure Mobility Client (version 4.10.03104):
taskkill -im vpnui.exe -f
"%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe" disconnect
SLEEP 3
"%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe" -s < credential.txt
SLEEP 8
"%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe"
The file "credential.txt" must contain three lines:
connect <host>
<login>
<password>
where <host> is IP address or hostname of the host to connect, <login> is your login, and <password> is your password. The first line taskkill -im vpnui.exe -f is nesessary for killing the GUI, because when the GUI is running the login through the command line doesn't work. The last line launches the GUI again after successive logon.
The same script written as a VBS file (suitable for Windows Task Sheduler):
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "taskkill -im vpnui.exe -f"
WshShell.Run """%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"" disconnect"
WScript.Sleep 3000
WshShell.Run "cmd /K ""%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe"" -s < credential.txt"
WScript.Sleep 8000
WshShell.Run """%PROGRAMFILES(x86)%\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe"""
Save this script as "login.vbs", and assign running it as an "Action" in the Windows Task Sheduler.