I'm trying to comment this lines:
passdb {
driver = pam
[session=yes] [setcred=yes] [failure_show_msg=yes] [max_requests=<n>]
[cache_key=<key>] [<service name>]
args = dovecot
}
via sed:
sed -i '1!N; s/passdb {\
driver = pam\
\[session=yes\] \[setcred=yes\] \[failure_show_msg=yes\] \[max_requests=\<n\>\]\
\[cache_key=\<key\>\] \[\<service name\>\]\
args = dovecot\
}/#passdb {\
# driver = pam\
# [session=yes] [setcred=yes] [failure_show_msg=yes] [max_requests=<n>]\
# [cache_key=<key>] [<service name>]\
# args = dovecot\
#}/' t
But it doesn't match what I need, can anyone tell me what I'm doing wrong here?
If all you are trying to do is comment the lines between passdb and }, then the following should suffice
sed -i '/^passdb {/,/}/s/^/#/g' file
Using awk
awk '/^passdb {/,/^}/ {$0="#"$0}1' file
Related
There is a similar question on SO, however, the provided answer is all done in one line. For readability purposes I would like the solution on multiple lines:
This is what I tried although as append:
sed -i '/home_server localhost {/a\
home_server example-coa {\
type = coa\
ipaddr = 127.0.0.1\
port = 3799\
secret = '"${SECRET}"'\
coa {\
irt = 2\
mrt = 16\
mrc = 5\
mrd = 30\
}\
}\
home_server localhost {\
' /etc/freeradius/3.0/proxy.conf
This is an example of APPEND, it works, but I need to do a replace.
I would like to replace home_server localhost { with the above.
I'm literally trying to add a block above it so that it will look like this at the end:
home_server example-coa {
...
}
home_server localhost {
...
}
Why don't you just insert? E.g
sed -i '/home_server localhost {/i\
home_server example-coa {\
type = coa\
ipaddr = 127.0.0.1\
port = 3799\
secret = '"${SECRET}"'\
coa {\
irt = 2\
mrt = 16\
mrc = 5\
mrd = 30\
}\
}\
' /etc/freeradius/3.0/proxy.conf
This might work for you (GNU sed and bash):
cat <<! | sed '/home_server localhost {/e cat /dev/stdin' file
home_server example-coa {
type = coa
ipaddr = 127.0.0.1
port = 3799
secret = '"${SECRET}"'
coa {
irt = 2
mrt = 16
mrc = 5
mrd = 30
}
}
!
Use the e command to place a here-document in the output stream of a sed command.
I want to extract comment from SCSS file put them on a new markdown file and remove the comments from original file.
file.scss
/***
* # Typography
* We use
* [Roboto](https://fonts.google.com/specimen/Roboto)
*/
/**
* Body typography:
* `p`
*
* #example
* p This is a paragraph with #[strong bold ] and#[em italic ] styles.</p>
*/
body {
color: $base-font-color;
}
/**
* Heading 1:
* `h1` `.h1`
*/
h1,
.h1 {
#include h1;
}
Expected result
At the end of the process I would like to have:
Comments.md
# Typography
* We use
[Roboto](https://fonts.google.com/specimen/Roboto)
Body typography:
`p`
#example
p This is a paragraph with #[strong bold ] and#[em italic ] styles.</p>
Heading 1:
`h1` `.h1`
file.scss
body {
color: $base-font-color;
}
h1,
.h1 {
#include h1;
}
Question
How can I do that with awk, perl, sed or other tools?
I implement a solution myself
#!/usr/bin/env bash
# USAGE
# ## Development
#
# # single file
# bash ./scripts/extract-md.bash src/base/_typography.scss
#
# # all files
# bash ./scripts/extract-md.bash src/base/_typography.scss
#
# ## production (override files)
#
# export PRODUCTION=true
# bash ./scripts/extract-md.bash
shopt -s globstar
start() {
for legacy in $legacies; do
directory="${legacy%/*}"
filename="${legacy##*/}"
new_filename="${filename//.scss/.md}"
documentation="${directory}/${new_filename}"
extract_comment "$legacy" "$documentation"
stylesheet="${1//.scss/.new.scss}"
extract_code "$legacy" "$stylesheet"
[[ $PRODUCTION ]] && mv "$stylesheet" "$legacy"
done
}
extract_comment() {
local legacy="$1"
local documentation="$2"
awk '/^\/\*/{flag=1} flag; /^\s?\*\//{print;flag=0}' "$legacy" \
| perl -p -e 's/\/[\*]+//g' \
| perl -p -e 's/^\s*[\*]?[ \/]?//g' \
> "$documentation"
}
extract_code() {
local legacy="$1"
local stylesheet="$2"
awk 'BEGIN{flag=1}/^\/\*/{flag=0}; /^\s?\*\//{flag=1; next}flag' "$legacy" \
> "$stylesheet"
}
legacies=${1:-src/**/*.scss}
start $legacies
Are there minimal, or even larger, working examples of using SCons and knitr to generate reports from .Rmd files?
kniting an cleaning_session.Rmd file from the command line (bash shell) to derive an .html file, may be done via:
Rscript -e "library(knitr); knit('cleaning_session.Rmd')".
In this example, Rscript and instructions are fed to a Makefile:
RMDFILE=test
html :
Rscript -e "require(knitr); require(markdown); knit('$(RMDFILE).rmd', '$(RMDFILE).md'); markdownToHTML('$(RMDFILE).md', '$(RMDFILE).html', options=c('use_xhtml', 'base64_images')); browseURL(paste('file://', file.path(getwd(),'$(RMDFILE).html'), sep=''
In this answer https://stackoverflow.com/a/10945832/1172302, there is reportedly a solution using SCons. Yet, I did not test enough to make it work for me. Essentially, it would be awesome to have something like the example presented at https://tex.stackexchange.com/a/26573/8272.
[Updated] One working example is an Sconstruct file:
import os
environment = Environment(ENV=os.environ)
# define a `knitr` builder
builder = Builder(action = '/usr/local/bin/knit $SOURCE -o $TARGET',
src_suffix='Rmd')
# add builders as "Knit", "RMD"
environment.Append( BUILDERS = {'Knit' : builder} )
# define an `rmarkdown::render()` builder
builder = Builder(action = '/usr/bin/Rscript -e "rmarkdown::render(input=\'$SOURCE\', output_file=\'$TARGET\')"',
src_suffix='Rmd')
environment.Append( BUILDERS = {'RMD' : builder} )
# define source (and target files -- currently useless, since not defined above!)
# main cleaning session code
environment.RMD(source='cleaning_session.Rmd', target='cleaning_session.html')
# documentation of the Cleaning Process
environment.Knit(source='Cleaning_Process.Rmd', target='Cleaning_Process.html')
# documentation of data
environment.Knit(source='Code_Book.Rmd', target='Code_Book.html')
The first builder calls the custom script called knit. Which, in turn, takes care of the target file/extension, here being cleaning_session.html. Likely the suffix parameter is not needed altogether, in this very example.
The second builder added is Rscript -e "rmarkdown::render(\'$SOURCE\')"'.
The existence of $TARGETs (as in the example at Command wrapper) ensures SCons won't repeat work if a target file already exists.
The custom script (whose source I can't retrieve currently) is:
#!/usr/bin/env Rscript
local({
p = commandArgs(TRUE)
if (length(p) == 0L || any(c('-h', '--help') %in% p)) {
message('usage: knit input [input2 input3] [-n] [-o output output2 output3]
-h, --help to print help messages
-n, --no-convert do not convert tex to pdf, markdown to html, etc
-o output filename(s) for knit()')
q('no')
}
library(knitr)
o = match('-o', p)
if (is.na(o)) output = NA else {
output = tail(p, length(p) - o)
p = head(p, o - 1L)
}
nc = c('-n', '--no-convert')
knit_fun = if (any(nc %in% p)) {
p = setdiff(p, nc)
knit
} else {
if (length(p) == 0L) stop('no input file provided')
if (grepl('\\.(R|S)(nw|tex)$', p[1])) {
function(x, ...) knit2pdf(x, ..., clean = TRUE)
} else {
if (grepl('\\.R(md|markdown)$', p[1])) knit2html else knit
}
}
mapply(knit_fun, p, output = output, MoreArgs = list(envir = globalenv()))
})
The only thing, now, necessary is to run scons.
I am struggling to send multiple commands to multiple hosts , i am using commands input from a file:
commands.txt
sh ip int bri
sh run
sh ver
hosts.txt
router 1
router 2
router 3
I then run following
from future import print_function from netmiko import ConnectHandler ##For SSH import re import getpass while True: #create loop for whole program username = input ("Enter Username") jumphostpassword = getpass.getpass("Enter Jumphost Password") elif (op == 2): TACACSpassword = getpass.getpass ("Enter TACACS Password") elif(in1=="c"): commandsfile = input ("Please Enter CommandsFile path as c:/example/ \n :") hostsfile = input ("Please Enter Hosts path as c:/example/ \n :") # hosts = open((hostsfile) , "r") hosts = [hosts for hosts in (hosts.strip() for hosts in open(hostsfile)) if hosts] for host1 in hosts: with open ( host1+".txt","w") as file: commands1 = open( (commandsfile), "r+") jumphost = {'device_type': 'linux','ip': '172.27.200.26', 'username': (username),'password': (jumphostpassword)} net_connect = ConnectHandler(**jumphost) output = net_connect.send_command("ssh " +str(host1)) print (output) else: output = net_connect.send_command(TACACSpassword) print (output) output = net_connect.send_command("term leng 0") print (output) cmd1 = [cmd1 for cmd1 in (cmd1.strip() for cmd1 in open(commandsfile)) if cmd1] for cmd1 in commands1: print ("File saved in c:\saad\saad.txt ") output += net_connect.send_config_set(cmd1) print (output) net_connect.disconnect print ("File saved in c:\saad\saad.txt ") file.write(output) file.close() continue
Place your IPs in ips.csv file in the following format...
Host
192.168.1.1
192.168.1.2
Then use the following code, usage python code.py -c ips.csv
#!/usr/bin/python
import getpass
import re
import csv
import paramiko
import netmiko
from argparse import ArgumentParser
from netmiko import ConnectHandler
if __name__ == '__main__':
parser = ArgumentParser(description='Arguments:')
parser.add_argument('-c', '--csv', required=True, action='store',
help='Location of CSV file of IPs')
args = parser.parse_args()
ssh_username = 'yoursshusername'
ssh_password = 'yoursshpassword'
with open(args.csv, 'r') as file:
reader = csv.DictReader(file)
for device_row in reader:
try:
ssh_session = ConnectHandler(device_type='cisco_ios',
ip=device_row['Host'],
username=ssh_username, password=ssh_password)
print '********* {0} *********'.format(device_row['Host'
])
# Specify your commands here, you can add more commands just follow the same syntax
print ssh_session.send_command('show running-config | i hostname')
# Specify exceptions here
except paramiko.AuthenticationException:
print ('{0}'.format(device_row['Host']),"Authenticaiton Problem!")
pass
I'm fairly new to Scala and need to build a really simple command line parser which provides something like the following which I created using JRuby in a few minutes:-
java -jar demo.jar --help
Command Line Example Application
Example: java -jar demo.jar --dn "CN=Test" --nde-url "http://www.example.com" --password "password"
For usage see below:
-n http://www.example.com
-p, --password set the password
-c, --capi set add to Windows key-store
-h, --help Show this message
-v, --version Print version
Scallop looks like it will do the trick, but I can't seem to find a simple example that works! All of the examples I've found seem to be fragmented and don't work for some reason or other.
UPDATE
I found this example which works, but I'm not sure how to bind it into the actual args within the main method.
import org.rogach.scallop._;
object cmdlinetest {
def main(args: Array[String])
val opts = Scallop(List("-d","--num-limbs","1"))
.version("test 1.2.3 (c) 2012 Mr Placeholder")
.banner("""Usage: test [OPTION]... [pet-name]
|test is an awesome program, which does something funny
|Options:
|""".stripMargin)
.footer("\nFor all other tricks, consult the documentation!")
.opt[Boolean]("donkey", descr = "use donkey mode")
.opt("monkeys", default = Some(2), short = 'm')
.opt[Int]("num-limbs", 'k',
"number of libms", required = true)
.opt[List[Double]]("params")
.opt[String]("debug", hidden = true)
.props[String]('D',"some key-value pairs")
// you can add parameters a bit later
.args(List("-Dalpha=1","-D","betta=2","gamma=3", "Pigeon"))
.trailArg[String]("pet name")
.verify
println(opts.help)
}
}
Well, I'll try to add more examples :)
In this case, it would be much better to use ScallopConf:
import org.rogach.scallop._
object Main extends App {
val opts = new ScallopConf(args) {
banner("""
NDE/SCEP Certificate enrollment prototype
Example: java -jar demo.jar --dn CN=Test --nde-url http://www.example.com --password password
For usage see below:
""")
val ndeUrl = opt[String]("nde-url")
val password = opt[String]("password", descr = "set the password")
val capi = toggle("capi", prefix = "no-", descrYes = "enable adding to Windows key-store", descrNo = "disable adding to Windows key-store")
val version = opt[Boolean]("version", noshort = true, descr = "Print version")
val help = opt[Boolean]("help", noshort = true, descr = "Show this message")
}
println(opts.password())
}
It prints:
$ java -jar demo.jar --help
NDE/SCEP Certificate enrollment prototype
Example: java -jar demo.jar --dn CN=Test --nde-url http://www.example.com --password password
For usage see below:
-c, --capi enable adding to Windows key-store
--no-capi disable adding to Windows key-store
--help Show this message
-n, --nde-url <arg>
-p, --password <arg> set the password
--version Print version
Did you read the documentation? It looks like all you have to do is call get for each option you want:
def get [A] (name: String)(implicit m: Manifest[A]): Option[A]
It looks like you might need to provide the expected return type in the method call. Try something like this:
val donkey = opts.get[Boolean]("donkey")
val numLimbs = opts.get[Int]("num-limbs")
If you're just looking for a quick and dirty way to parse command line arguments, you can use pirate, an extremely barebones way to parse arguments. Here is what it would look like to handle the usage you describe above:
import com.mosesn.pirate.Pirate
object Main {
def main(commandLineArgs: Array[String]) {
val args = Pirate("[ -n string ] [ -p string ] [ -chv ]")("-n whatever -c".split(" "))
val c = args.flags.contains('c')
val v = args.flags.contains('v')
val h = args.flags.contains('h')
val n = args.strings.get("n")
val p = args.strings.get("p")
println(Seq(c, v, h, n, p))
}
}
Of course, for your program, you would pass commandLineArgs instead of "-n whatever -c".
Unfortunately, pirate does not yet support GNU style arguments, nor the version or help text options.