Use expect.Expect for Groovy to SSH on specific port - groovy

Have a simple groovy script as follows (terribly formatted):
import com.santaba.agent.groovyapi.expect.Expect
def hostname = hostProps.get("system.hostname")
cli = Expect.open(hostname, "user", "pass")
cli.expect("*** Welcome to pfSense ")
cli.send("8\n")
cli.expect("root(1): ")
cli.send( "relayctl show hosts\n" )
cli.expect("root(2): ")
cli.before().eachLine { line ->
if ( line =~ /host/ ) {
tokens = line.split(/\s+/)
println tokens[5]
}
}
cli.send("exit\n")
cli.close()
What I'm unable to do is to pass in the PORT I'd like for it to SSH on, for example: 8331.
Is it possible to achieve this? Thanks!

It looks like you can send in the port number as part of the .open call:
cli = Expect.open(hostname, 8331, 5)//port 8331, 5 connection retries
Should be able to figure the rest of the commands from the logic monitor docs

Related

How to obtain virtual user id/details in gatling?

I am new to Gatling and Scala and I need your advice.
I would like to obtain load test for n-users. Each user have to send request for creating different accounts. This is obtained by sending json file with appropriate array of objects ('entries' in our case).
Each single user must send different login as our backend system is checking if username is unique. Somehow we have to be sure that gatling is sending different data for each virtual user and also for each entries as well.
We noticed that there us session element which represents virtual user's state. Problem is that code showed below will not work as Exec structure used with expression function does not send any request.
There is section that could work but I do not know how to determine third parameter to distinguish virtual user id. Please find below simple json file structure used for this test
{
"entries": [
{
"userName": "some user name",
"password": "some password"
}
}
and scala code with my comments
import io.gatling.core.Predef._
import io.gatling.http.Predef._
class UserCreationTest extends Simulation {
val profilesNumber = 2
val virtualUsers = 2
val httpConf = http
.baseURL("some url")
.acceptHeader("application/json")
.basicAuth("username", "password")
// This method will multiply 'entries' section in JSON 'entriesNumber' times
def createJsonUserEntries(entriesNumber: Int, users: List[String], userId : Long): String = {
val header = """{"entries": ["""
val footer = """]}"""
val builder = StringBuilder.newBuilder
for (i <- 0 until entriesNumber) {
val userIndex = (userId.toInt - 1) * entriesNumber + i
val userName = users(userIndex).get
val apiString =
s"""{
"userName": "${userName}"
"password": "password"
}"""
builder.append(apiString)
if (i != entriesNumber) {
builder.append(",")
}
}
header + builder.toString() + footer
}
// We do have method for generating user names based on profilesNumber and virtualUsers variables
// but for sake of this example lets hardcode 4 (profilesNumber * virtualUsers) user names
val usersList = List("user-1", "user-2", "user-3", "user-4")
//This will throw exception as no request was send. According to documentation function block is used to debugging/editing session
val scn = scenario("Create WiFi User Profile")
.exec(session => {
http("CreateUserProfile")
.post("/userProfiles/create/")
.body(StringBody(
createJsonUserEntries(profilesNumber, userslList, session.userId).toString
)
).asJSON
session})
// This exec block will send a request but I do not know how to determine third param that should be virtual user Id
// To run this section please comment previous whole scenario block
/*
val scn = scenario("")
.exec(http("CreateUserProfile")
.post("/userProfiles/create/")
.body(StringBody(
createJsonUserEntries(profilesNumber, emailList, ???).toString
)
).asJSON
)
*/
setUp(scn.inject(atOnceUsers(virtualUsers)).protocols(httpConf))
}
Can you help me on that please? Is there any other way to do that in gatling? Thank you very much in advance
so you are trying to have each user have a unique userId?
you could create a feeder that does this
var userIdFeeder = (1 to 999999).toStream.map(i => Map("userId" -> i)).toIterator
val scn = scenario("")
.feed(userIdFeeder)
.exec(http("CreateUserProfile")
.post("/userProfiles/create/")
.body(StringBody(
createJsonUserEntries(profilesNumber, emailList, "${userId}").toString
)
).asJSON
)

Search a string with Javascript

Hi everyone,
I am trying to test C programs that use an user input... Like a learning app. So the avaliator(teacher) can write tests and I compile the code with a help of a docker and get back the result of the program that I send. After that I verify if one of the case tests fails..
for that I have two strings, like this:
result = "input_compiled1540323505983: /home/compiler/input/input.c:9: main: Assertion `B==2' failed. timeout: the monitored command dumped core Aborted "
and an array with case tests that is like:
caseTests = [" assert(A==3); // A must have the value of 3;", " assert(B==2); // B must have the value of 2; ", " assert(strcmp(Fulano, "Fulano")==0); //Fulano must be equal to Fulano]
I need to send back from my server something like this:
{ console: [true, true, true ] }
Where each true is the corresponding test for every test in the array of tests
So, I need to test if one string contains the part of another string... and for now I did like this:
criandoConsole = function(arrayErros, arrayResult){
var consol = arrayErros.map( function( elem ) {
var local = elem.match(/\((.*)\)/);
if(arrayResult.indexOf(local) > -1 ) {
return false;
}
else return true;
});
return consol;
}
I am wondering if there are any more efective way of doing that. I am using a nodejs as server. Does anyone know a better way?!
ps: Just do like result.contains(caseTests[0]) did not work..
I know this is changing the problem, but can you simplify the error array to only include the search terms? For example,
result = "input_compiled1540323505983: /home/compiler/input/input.c:9: main: Assertion `B==2' failed. timeout: the monitored command dumped core Aborted ";
//simplify the search patterns
caseTests = [
"A==3",
"B==2",
"strcmp(Fulano, \"Fulano\")==0"
]
criandoConsole = function(arrayErros, arrayResult){
var consol = arrayErros.map( function( elem ) {
if (arrayResult.indexOf(elem) != -1)
return false; //assert failed?
else
return true; //success?
});
return consol;
}
console.log(criandoConsole(caseTests,result));

jenkins Slave API setLabelString adds to User list

I have the following script under a JOB, which when run adds the userId to the label of the slave.
import jenkins.model.Jenkins
import hudson.model.User
import hudson.security.Permission
import hudson.EnvVars
EnvVars envVars = build.getEnvironment(listener);
def userId= envVars .get('BUILD_USER_ID')
def nodeName= envVars .get('NODE_NAME')
def nodeOffpool= envVars .get('NODE_GOING_OFFPOOL')
allUsers = User.getAll()
println allUsers
println ""
// add userid as a label if doesnot exist
for (slave in hudson.model.Hudson.instance.slaves) {
if( slave.nodeName.equals(nodeOffpool)) {
def labelList = (slave.getLabelString()).split()
println labelList
// check for user access to machine
for(label in labelList) {
println (User.get(label))
println (User.get(label) in allUsers)
if (User.get(label) in allUsers) {
if (label == userId) {
println ("This Node has already been assigned to you ($userId)")
} else {
println ("This Node($nodeOffpool) has already been assigned to someone($label) else, you cannot use it now")
println ("Please ask the user $label to release the Node($nodeOffpool) for you($label) to run")
}
return
}
};
println ("before: " + slave.getLabelString())
// setting the slave with new label
String newLabel = slave.getLabelString() + " " + userId
slave.setLabelString(newLabel)
println ("after: " + slave.getLabelString())
}
}
When i run for the first time output looks fine
[user1, user2, SYSTEM, unknown]
[TESTLAB3, TESTLAB4]
TESTLAB3
false
TESTLAB4
false
before: TESTLAB3 TESTLAB4
after: TESTLAB3 TESTLAB4 user1
When i run the second time
[user1, user2, SYSTEM, unknown, TESTLAB3, TESTLAB4]
[TESTLAB3, TESTLAB4, user1]
TESTLAB3
true
This Node(node1) has already been assigned to someone(TESTLAB3) else, you cannot use it now
Please ask the user TESTLAB3 to release the Node(node1) for you(TESTLAB3) to run
Finished: SUCCESS
Is this issue with Jenkins API. I am using Jenkins 1.573
related questions:
How to identify admins on Jenkins using groovy scripts
jenkins change label as requested
Updated:
I found out the answer by trail and error.
User.get(label)
adds the label as user if it doesnt exist by default. To prevent this addition, we have to use
User.get(label, false)
You are adding the username to the slave's label. Printing User.getAll() just prints the list of users for your Jenkins, not the slave's labels, which you modified with the user name.
Here is a script you can use to test if your slave machines have the new labels added to them:
for (slave in jenkins.model.Jenkins.instance.slaves) {
print "Slave: " + slave.getNodeName() + "\n";
print "Label: " + slave.getLabelString() + "\n\n";
}
Also, you might want to change the script so that it only sets the new label for the Slave if it doesn't already contain the user, because you will be adding it multiple times every time the script is run the way it's written now.

Can I use nested scoping when specifying environments in ConfigSlurper?

Using Groovy 2.0.7, when I have a config.groovy such as:-
def configText = """
switch(environment) {
case 'localhost':
PROXY {
HOST = "localproxy"
}
break
}
PROXY {
HOST = "defaultproxy"
}"""
def config = new ConfigSlurper("localhost").parse(configText)
, I get an assertion failure when I do this:-
assert "localproxy" == config.PROXY.HOST
If I remove the "defaultproxy" line then the environment value is correctly returned.
Am I doing something wrong? This to me is a standard requirement, to have a default value specified for config.PROXY.HOST but be able to override it in the environments switch block.
I know I can use the environments constructor to override the values but that is no use to me as it doesn't allow me to evaluate values, e.g. if I had:-
PROXY {
HOST = "defaultproxy"
URL = "http://" + HOST
}
then the URL would always be http://defaultproxy even if I specified the "localhost" environment.
I need the features from both really! Anyone know how I can achieve this?
You could also put the switch statement after the default proxy.host property...
def configText = """
PROXY {
HOST = "defaultproxy"
}
switch(environment) {
case 'localhost':
PROXY {
HOST = "localproxy"
}
break
}
"""
def config = new ConfigSlurper("localhost").parse(configText)
assert "localproxy" == config.PROXY.HOST
or you could leverage the environment property like this:
def configText = """
PROXY {
HOST = "defaultproxy"
}
environments{
localhost{
PROXY.HOST='localproxy'
}
}
"""
def config = new ConfigSlurper("localhost").parse(configText)
assert "localproxy" == config.PROXY.HOST
OK, I have a solution which works.
I wrapped the switch statement into a function, then called the function at the top of the script (below the function, above the nested scoped properties) and then called the function again at the bottom.
Crude, horrible, but works. If anyone has a better solution, please let me know!

Jira Groovy script in script runner

I'm trying to get users not in the jira-users group with email addresses not equal to: email#email.com. I can get the users not in the jira-users group(see below) but not sure how to complete the if statement to show "users email address not equal to email#email.com. I tried user.getEmail but couldn't get that to work. Would someone be able to make a suggestion with this?
Thanks.
for ( user in crowdService.search(query) ) {
if (!crowdService.isUserMemberOfGroup(user.getName(), "jira-users")) {
body = body + user.getName() + "\n"
}
}
The User object implementation depends on your particular Atlassian setup.
Try calling user.getEmailAddress():
for ( user in crowdService.search(query) ) {
if (!crowdService.isUserMemberOfGroup(user.getName(), "jira-users")
&& !user.getEmailAddress().equals("email#email.com")) {
body = body + user.getName() + "\n"
}
}

Resources