• Stars
    star
    7
  • Rank 2,221,022 (Top 46 %)
  • Language
    Ruby
  • License
    MIT License
  • Created about 5 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A library to make interactive SSH sessions more convenient.

Net::SSH::CLI

Adds another layer on top of Net::SSH for a proper handling of CLI sessions which last longer than one command. This is especially usefull for enterprise Switches and Routers.

Installation

Add this line to your application's Gemfile:

gem 'net-ssh-cli'

And then execute:

$ bundle

Or install it yourself as:

$ gem install net-ssh-cli

Features

  • provides an abstraction on top of the text-stream of a long living CLI sessions
  • tries to be highly configurable
  • has methods like #cmd and #dialog for common usecases
  • offers waiting operations like #read_till

Usage

Net::SSH.start('host', 'user', password: "password") do |ssh|
  cli = ssh.cli(default_prompt: /(\nuser@host):/m)
  cli.cmd ""
  # => "Last login: \nuser@host:"

  cli.cmd "echo 'bananas'"
  # => "echo 'bananas'\nbananas\nuser@host:"
end
  net_ssh = Net::SSH.start('host', 'user', password: "password")
  cli = Net::SSH::CLI::Session.new(net_ssh: net_ssh)
  cli.cmd ""
  cli = Net::SSH::CLI::Session.new(net_ssh_options: {host: 'host', user: 'user', password: 'password'})
  cli.cmd ""

#cmd

  cli = ssh.cli(default_prompt: /(\nuser@host):/m)
  cli.cmd "echo 'bananas'"
  # => "echo 'bananas'\nbananas\nuser@host:"
  cli.cmd "echo 'bananas'", rm_command: true
  # => "bananas\nuser@host:"
  cli.cmd "echo 'bananas'", rm_prompt: true
  # => "echo 'bananas'\nbananas"
  cli.cmd "echo 'bananas'", rm_command: true, rm_prompt: true
  # => "bananas"
  cli.cmd "echo 'bananas'", rm_command: true, rm_prompt: true, minimum_duration: 9
  # => "bananas"
  cli.cmd "echo 'bananas'", rm_command: true, rm_prompt: true, prompt: /\nuser@host:/m
  # => "bananas"
  cli.cmd "echo 'bananas'", rm_command: true, rm_prompt: true, timeout: 60
  # => "bananas"

Remove the command and the prompt for #cmd & #dialog by default

  cli = ssh.cli(default_prompt: /(\nuser@host):/m, cmd_rm_command: true, cmd_rm_prompt: true)
  cli.cmd "echo 'bananas'"
  # => "bananas"

You can define a timeout for a #cmd in order to avoid hanging commands. The timeout gets passed into the underlying function #read_till. This is usefull in case your prompt won't match because of an unexpected behaviour or undefined behaviour. For example some form of unexpected dialog. The underlying implementation is using a soft timeout because Timeout.timeout is dangerous. In order to deal anyway with hanging low level issues, Timeout.timeout is used too, but with a higher value than the soft timeout.

  cli = ssh.cli(default_prompt: /(\nuser@host):/m, read_till_timeout: 11)
  cli.cmd "echo 'bananas'"                      # timeout is set to 11
  # => "bananas"
  cli.cmd "echo 'bananas'", timeout: 22         # timeout is set to 22
  # => "bananas"
  cli.cmd "sleep 33", timeout: 22               # timeout is set to 22
  # Net::SSH::CLI::Error::CMD

#cmds

It's the same as #cmd but for multiple commands.

  cli.cmds ["echo 'bananas'", "echo 'apples'"], rm_command: true, rm_prompt: true
  # => ["bananas", "apples"]

#dialog

Use this method to specify a differnt 'prompt' for once. This is perfect for interactive commands.

  cli.dialog "echo 'are you sure?' && read -p 'yes|no>'", /\nyes|no>/
  # => "echo 'are you sure?' && read -p 'yes|no>'\nyes|no>"
  cli.cmd "yes"
cli.dialog "passwd", /Current Password:/i
cli.dialog "Old Password", /New Password:/i
cli.dialog "New Password", /Repeat Password:/i
cli.cmd "New Password"

#impact

The very same as #cmd but it respects a flag whether to run commands with 'impact'. This can be used in a setup where you don't want to run certain commands under certain conditions. For example in testing.

  cli.run_impact?
  # => false
  cli.impact "reboot now"
  # => "skip: 'reboot now'"
  cli.run_impact = true
  cli.impact "reboot now"
  # => connection closed

#read & #write

  cli.write "echo 'hello'\n"
  # => "echo 'hello'\n"
  cli.read
  # => "echo 'hello'\nhello\nuser@host:"

#write_n

  cli.write_n "echo 'hello'"
  # => "echo 'hello'\n"

#read_till

keep on processing till the stdout matches to given|default prompt and then read the whole stdin.

  cli.write "echo 'hello'\n"
  # => "echo 'hello'\n"
  cli.read_till
  # => "echo 'hello'\nhello\nuser@host:"

This method is used by #cmd, see lib/net/ssh/cli.rb#cmd

#read_for

  cli.write_n "sleep 180"
  # => ""
  cli.read_for(seconds: 181)
  # => "..."

Configuration

Have a deep look at the various Options configured by Net::SSH::CLI::OPTIONS in lib/net/ssh/cli.rb Nearly everything can be configured.

Callbacks

The following callbacks are available

  • before_open_channel
  • after_open_channel
  • before_on_stdout
  • after_on_stdout
  • before_on_stdin
  • after_on_stdin
cli.before_open_channel do
  puts "The channel will open soon"
end
cli.after_open_channel do
  cmd "logger 'Net::SSH::CLI works'"
  cmd "sudo -i"
end

Using the callbacks you can define a debugger which shows the stdout buffer content each time new data is received.

cli.after_on_stdout do
  warn stdout
end
cli.after_on_stdout do
  puts "the following new data arrived on stdout #{new_data.inspect} from #{hostname}"
end

or convert new lines between different OS

cli.after_on_stdout do
  stdout.gsub!("\r\n", "\n")
end

or hide passwords

cli.after_on_stdout do
  stdout.gsub!(/password:\S+/, "<HIDDEN>")
end

or change the stdin before sending it

cli.before_on_stdin do
  content.gsub("\n\n", "\n")
end

#hostname #host #to_s

  cli.to_s
  # => "localhost"
  cli.hostname
  # => "localhost"
  cli.host
  # => "localhost"

#detect_prompt

NET::SSH::CLI can try to guess the prompt by waiting for it and using the last line. This works usually, but is not guaranteed to work well.

  cli.open_channel
  # => ...
  cli.detect_prompt(seconds: 3)
  # => "[my prompt]"

An outdated view of all available Options

Please check the file lib/net/ssh/cli.rb OPTIONS in order to get an up-to-date view of all available options, flags and arguments.

      OPTIONS = ActiveSupport::HashWithIndifferentAccess.new(
        default_prompt:            /\n?^(\S+@.*)\z/,                             # the default prompt to search for
        cmd_rm_prompt:             false,                                        # whether the prompt should be removed in the output of #cmd
        cmd_rm_command:            false,                                        # whether the given command should be removed in the output of #cmd
        cmd_rm_command_tail:       "\n",                                         # which format does the end of line return after a command has been submitted. Could be something like "ls\n" "ls\r\n" or "ls \n" (extra spaces)
        run_impact:                false,                                        # whether to run #impact commands. This might align with testing|development|production. example #impact("reboot")
        read_till_timeout:         nil,                                          # timeout for #read_till to find the match
        read_till_hard_timeout:    nil,                                          # hard timeout for #read_till to find the match using Timeout.timeout(hard_timeout) {}. Might creates unpredicted sideffects
        read_till_hard_timeout_factor: 1.2,                                      # hard timeout factor in case read_till_hard_timeout is true
        named_prompts:             ActiveSupport::HashWithIndifferentAccess.new, # you can used named prompts for #with_prompt {} 
        before_cmd_procs:          ActiveSupport::HashWithIndifferentAccess.new, # procs to call before #cmd 
        after_cmd_procs:           ActiveSupport::HashWithIndifferentAccess.new, # procs to call after  #cmd
        before_on_stdout_procs:    ActiveSupport::HashWithIndifferentAccess.new, # procs to call before data arrives from the underlying connection 
        after_on_stdout_procs:     ActiveSupport::HashWithIndifferentAccess.new, # procs to call after  data arrives from the underlying connection
        before_on_stdin_procs:     ActiveSupport::HashWithIndifferentAccess.new, # procs to call before data is sent to the underlying channel 
        after_on_stdin_procs:      ActiveSupport::HashWithIndifferentAccess.new, # procs to call after  data is sent to the underlying channel
        before_open_channel_procs: ActiveSupport::HashWithIndifferentAccess.new, # procs to call before opening a channel 
        after_open_channel_procs:  ActiveSupport::HashWithIndifferentAccess.new, # procs to call after  opening a channel, for example you could call #detect_prompt or #read_till
        open_channel_timeout:      nil,                                          # timeout to open the channel
        net_ssh_options:           ActiveSupport::HashWithIndifferentAccess.new, # a wrapper for options to pass to Net::SSH.start in case net_ssh is undefined
        process_time:              0.00001,                                      # how long #process is processing net_ssh#process or sleeping (waiting for something)
        background_processing:     false,                                        # default false, whether the process method maps to the underlying net_ssh#process or the net_ssh#process happens in a separate loop
        on_stdout_processing:      100,                                          # whether to optimize the on_stdout performance by calling #process #optimize_on_stdout-times in case more data arrives
        sleep_procs:               ActiveSupport::HashWithIndifferentAccess.new, # procs to call instead of Kernel.sleep(), perfect for async hooks
      )

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/swisscom/net-ssh-cli.

License

The gem is available as open source under the terms of the MIT License.

More Repositories

1

ai-research-keyphrase-extraction

EmbedRank: Unsupervised Keyphrase Extraction using Sentence Embeddings (official implementation)
Python
427
star
2

cleanerversion

CleanerVersion adds a versioning/historizing layer to your relational DB which implements a "Slowly Changing Dimensions Type 2" behavior
Python
136
star
3

Invoke-Forensics

Invoke-Forensics provides PowerShell commands to simplify working with the forensic tools KAPE and RegRipper.
PowerShell
103
star
4

open-service-broker

Open Service Broker is an implementation of the "Open Service Broker API" based on Spring Boot & Groovy. It enables platforms such as Cloud Foundry & Kubernetes to provision and manage services.
Groovy
71
star
5

bugbounty

Swisscom Vulnerability Disclosure Policy & Bug Bounty Programme
64
star
6

ArtifactCollectionMatrix

Forensic Artifact Collection Tool Matrix
60
star
7

PowerGRR

PowerGRR is an API client library in PowerShell working on Windows, Linux and macOS for GRR automation and scripting.
PowerShell
56
star
8

detections

Threat intelligence and threat detection indicators (IOC, IOA)
YARA
51
star
9

PowerSponse

PowerSponse is a PowerShell module focused on targeted containment and remediation during incident response.
PowerShell
36
star
10

ruby-netsnmp

SNMP library in ruby (v1, v2c, v3)
Ruby
32
star
11

gitlab-merge-request-resource

A concourse resource to check for new merge requests on GitLab
Shell
31
star
12

cf-statistics-plugin

CloudFoundry CLI plugin for displaying real-time metrics and statistics data
Go
27
star
13

ai-research-mamo-framework

A Model Agnostic Multi-Objective Framework for Deep Learning models
Python
27
star
14

splunk-addon-powershell

Splunk Add-on for PowerShell provides field extraction for PowerShell event logs.
17
star
15

korp

A command line tool for pushing docker images into a corporate registry based on Kubernetes yaml files
Go
16
star
16

update-java-ca-certificates

Small utility to convert the system trust store to a system Java KeyStore
Go
15
star
17

bitbucket-cli

A Bitbucket Enterprise CLI
Go
14
star
18

cf-reverse-proxy

Proxy app to make your your HTTP backends publicy accessible
JavaScript
11
star
19

puppet-scaleio

Ruby
9
star
20

dynstrg-howto

JavaScript
9
star
21

collectd-scaleio

A collectd plugin for scaleio
Python
8
star
22

dopi

Deployment Orchestrator for Puppet - inner Orchestrator
Ruby
8
star
23

waypoint-plugin-cloudfoundry

A plugin for Hashicorp Waypoint that allows to deploy artifacts on Cloud Foundry
Go
8
star
24

mongodb-enterprise-boshrelease

A bosh release for MongoDB Enterprise.
Shell
7
star
25

swisscom-csirt-resources

A curated list of analysis tools and resources created or maintained by Swisscom CSIRT.
7
star
26

cf-workshop

Resources to host a Cloud Foundry workshop
Java
7
star
27

dop_common

Shared library for Deployment Orchestrator for Puppet
Ruby
7
star
28

searchdump

A simple tool to backup *Search (e.g: ElasticSearch / OpenSearch) to multiple destinations
Go
7
star
29

cf-sample-app-python

A sample Flask application to deploy to Cloud Foundry which works out of the box.
Python
7
star
30

ai-research-fairsourcing

This project provides actionable insights to improve Fairness and Diversity metrics during the recruiting pipeline of a company. It assesses the impact of each candidate with respect to the team's objectives. You can select the desired dimensions to consider as well as what are the relevant subgroups. Track your progress through time and adapt your targets!
Jupyter Notebook
7
star
31

dopv

Deployment Orchestrator for Puppet VM provisioning
Ruby
7
star
32

apisix-opa-plugin

Go
6
star
33

mip

Mobile Insights Platform
Python
6
star
34

dcsplus-utils

Helpful utilities for DCS+ users
PowerShell
5
star
35

pongo2-runner

A small utility to render pongo2 templates
Go
5
star
36

cf-sample-app-nodejs

A sample Express application to deploy to Cloud Foundry which works out of the box.
JavaScript
5
star
37

dopc-client

Deployment Orchestrator for Puppet - Controller Client
Ruby
5
star
38

dopc

Deployment Orchestrator for Puppet - Controller
Ruby
5
star
39

terraform-dcs-demo

This repo contains sample infrastructure as code snippets to deploy, maintain and manage infrastructure on DCS using Terraform vCloud Director provider.
HCL
5
star
40

cf-rasa-chatbot

Go
4
star
41

docs-api

The documentation of the Swisscom APIs
HTML
4
star
42

sample-uaa-spring-boot-service-provider

Java
4
star
43

ip-whitelisting-route-service-demo-app

A demo app for an IP whitelisting route service in Cloud Foundry
Go
4
star
44

docs-appcloud-service-offerings

The documentation to the services in the Swisscom Application Cloud marketplace
HTML
4
star
45

docs-k8wms

Documentation of the kubernetes workload management stack with github pages
4
star
46

churn-intent-DE

3
star
47

sample-uaa-spring-boot-resource-server

Java
3
star
48

blogpost-cnb

Resources used in the blog post "Cloud Native Buildpacks to unite PaaS and CaaS"
Java
3
star
49

renovate-approve-bot-bitbucket-server

Bot to automatically approve Bitbucket Server PRs
Go
3
star
50

mssql-always-encrypted

An utils library to work with MSSQL Always Encrypted features
Go
3
star
51

mac-fan

A small collection of utilities to control your Macbook fan speed.
Shell
3
star
52

appcloud-cf-cli-plugin

The official cf CLI plugin for the Swisscom Application Cloud
Go
3
star
53

securitytxt

Swisscom security contacts according to RFC 9116
3
star
54

provider-cortex

Go
2
star
55

esbuild-webserver

A simple web-server that can be used as an alternative to Webpack's dev-server
Go
2
star
56

ssl-tool

A tool to deal with SSL things
Go
2
star
57

esc-vm-scheduler-helm-chart

Helm Chart for the Swisscom ESC VM-Scheduler
2
star
58

ai-research-document-classification

Python
2
star
59

kube-tools

A collection of small tools to work with Kubernetes
Go
2
star
60

aws-generate-secrets

Go
2
star
61

cf-elk-sample

Example app for using ELK Service with NodeJS
JavaScript
2
star
62

opa-demo

An Open Policy Agent demo - source of the code used at WeAreDevelopers Live 2020
Go
2
star
63

puppet-package_verifiable

The idea is that we have a way to check within the catalog whether a package currently installed matches the one we want to install.
Ruby
2
star
64

sample-uaa-angular-client

Oidc sample app for Angular
TypeScript
2
star
65

mcollective-cmd-agent

This is a fork of the puppetlabs shell agent with ruby 1.8.7 support and additional features. https://github.com/puppetlabs/mcollective-shell-agent
Ruby
2
star
66

eos

EOS is a simple IPTV middleware prepared mainly for Android AOSP environment. It is a framework which can be easily ported to a target platform.
C
2
star
67

hfc

Ruby
1
star
68

docs-appcloud-service-connector

HTML
1
star
69

pod-lifecycle-notifier

A simple probe that notifies defined channels about its own startup and shutdown.
Java
1
star
70

kibana-buildpack

Go
1
star
71

istioports

A small app which adds large port ranges to an Istio ServiceEntry
Go
1
star
72

open-service-broker-extension-template

A template to show how Swisscom's service broker could be extended
Groovy
1
star
73

docs-dop

HTML
1
star
74

sample-uaa-javascript-client

Oidc (authorization code with PKCE) sample javascript app
HTML
1
star
75

cf-scraper

A simple app which scrapes information about Cloud Foundry orgs
JavaScript
1
star
76

crossplane-composition-tester

BDD test framework for the Crossplane compositions implemented with functions
Python
1
star
77

cf-sample-app-go

A sample Go application to deploy to Cloud Foundry which works out of the box.
Go
1
star
78

docs-appcloud-devguide

The documentation for developers working with the Swisscom Application Cloud
HTML
1
star
79

kubernetes-testing

A simple Kubernetes test suite
Ruby
1
star
80

cf-sample-app-dotnetcore

A sample ASP.NET application to deploy to Cloud Foundry which works out of the box.
C#
1
star
81

gte

Inspired by the dockerize template library, GTE is a go template engine based on the golang template package and the go-jmespath library (JMESPath is a query language for JSON).
Go
1
star
82

cf-default-app-staticfile

The default Static File app that will be pushed into the Swisscom Application cloud if no source code is provided.
HTML
1
star