The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2,482 other followers

Archive for the ‘xargs’ Category

Some links on xargs simulation in PowerShell

Posted by jpluimers on 2021/10/13

On nx, I’m used to xargs which allows to convert from a pipe of output into arguments passed to a command. This is useful, as many commands only accept arguments as parameters.

In PowerShell, you can usually avoid an xargs equivalent because commandlet output is a stream of objects that you can post-process using . I for instance used that in PowerShell: recovering from corrupt empty *.nupkg files after a disk was accidentally full during update.

Here are some xargs equivalency examples:

  • [WayBack] PowerShell tips for bash users, part 1 • Five

    xargs

    Xargs is one of the most powerfull UNIX commands. It is used to build and execute command lines from standard input. For example:
    $ cat dirs | xargs mkdir
    will use cat to take the strings (be it newline or blank character separated) from file ‘dirs’ and pass them through pipe to xargs which will then send one by one line as argument to mkdir which will then create those dirs or complain if those are existent.

    PowerShell equivalent:

    PS> cat dirs | %{mkdir $_}

    There is no ‘xargs’ command in PS, but you can use ‘foreach ‘ loop and pass the piped variable ‘$_’ to the mkdir. Shorthand for ‘foreach’ is ‘%’. This time also only newlines will separate the strings apart. If multiple strings separated by blanks are found in same line, mkdir will create a directory with blanks in the name, while we must quote to have the same in bash:

    $ cat dirs | sed 's|^|"|g' | sed 's|$|"|g' |xargs mkdir

  • [WayBack] What’s the equivalent of xargs in PowerShell? – Stack Overflow

    Q

    The POSIX-defined xargs command takes all of the items it receives from standard input and passes them as command-line arguments to the command it receives on it’s own command line. E.g: grep -rn "String" | xargs rm.

    What’s the equivalent in PowerShell?

    The following questions all ask this:

    but there is no correct answer because all the answers either use ForEach-Object, which will process items one-at-a-time (like xargs -n1) which gets the desired result for the examples given, or store the intermediate result in a variable, which offends my functional commandline-fu.

    A

    There are two ways that I’ve found. The first is probably more idiomatic PowerShell, and the second is more true to the pipe-based spirit of xargs.

    As an example, let’s say we want to pass all our cat pics to myapp.exe.

    Method #1: Command substitution

    You can do something similar to using $(command substitution) in sh by embedding your pipeline in the command string:

    &"myapp.exe" @(Get-ChildItem -Recurse -Filter *.jpg | Another-Step)

    The @(...) creates an array from the command inside it, and PowerShell automatically expands arrays passed to & into seperate command-line parameters.

    However, this does not really answer the question, because it will only work if you have control over the command you want to pass to, which may not be the case.

    Method #2: True piping

    You can also construct a “double pipeline” by having a sub-expression to pipe your objects, collecting them to an array, and then piping the array to your final command.

    ,@(Get-ChildItem -Recurse -Filter *.jpg | Another-Step) | %{&"myapp.exe" $_}

    The @(...) as before collects the items into an array, and the array is then piped to the final command which is invoked using % (ForEach-Object). Ordinarily, this would then loop over each item individually, because PowerShell will automatically flatten the array when it’s piped, but this can be avoided by prepending the , operator. The $_ special variable is then used as normal to embed the passed array.

    So the key is to wrap the pipeline you want to collect in ,@(...), and then pipe that to something in %{...}.

References

–jeroen

Posted in Software Development, Development, CommandLine, Power User, *nix, PowerShell, Scripting, PowerShell, bash, *nix-tools, xargs | Leave a Comment »

firewalld: show interfaces with their zone details and show zones in use

Posted by jpluimers on 2021/08/26

A while ago openSUSE switched to firewalld as a fronte-end for iptables. Tumbleweed was first in 2018, so I wrote a reminder: On my research list: migrate from OpenSuSE SuSEfirewall2 to firewalld « The Wiert Corner – irregular stream of stuff.

The core concept of firewalld is zones, which some people find hard to understand: [Archive.is/WayBack] Firewalld on Leap 15 – why is it so complicated ? : openSUSE.

Another concept is interfaces and how they bind to zones. [Wayback] Masquerading and Firewalls | Security Guide | openSUSE Leap 15.2 shows more of that.

The final concept is services that bind one or more aspects (like ports or addresses) to a service name [Wayback] Documentation – Manual Pages – firewalld.service | firewalld.

Other interesting bits of information:

Below are some examples on what I learned, especially finding details about active interfaces and the zones they are bound to.

All of them are based on:

  • the xargs shell trick (I known you can do some of them without the trick, but I try to use common patterns in my solution so I do not have to remember which boundary case fails
  • the echo -n trick to skip the newline output
  • the [WayBack] firewall-cmd options (which kind of care commands)
    • --get-active-zones:

      Print currently active zones altogether with interfaces and sources used in these zones. Active zones are zones, that have a binding to an interface or source. The output format is:

      zone1
        interfaces: interface1 interface2 ..
        sources: source1 ..
      zone2
        interfaces: interface3 ..
      zone3
        sources: source2 ..

      If there are no interfaces or sources bound to the zone, the corresponding line will be omitted.

    • --list-interfaces:

      List interfaces that are bound to zone zone as a space separated list. If zone is omitted, default zone will be used.

    • --get-zone-of-interface=<zone>:

      Print the name of the zone the interface is bound to or no zone.

    • --info-zone=<zone> (which shows far more information than the manual indicates):

      Print information about the zone zone. The output format is:

      zone
        interfaces: interface1 ..
        sources: source1 ..
        services: service1 ..
        ports: port1 ..
        protocols: protocol1 ..
        forward-ports: forward-port1 ..
        source-ports: source-port1 ..
        icmp-blocks: icmp-type1 ..
        rich rules: rich-rule1 ..

Two more notes before the examples:

  1. My first hunch was to use --list-all-zones, but that shows details of all un-used zones as well.
  2. I am not fully sure about the --list-interfaces to list *all* interfaces. I might replace this later with ls /sys/class/net (see [WayBack] linux – List only the device names of all available network interfaces – Super User).

Other useful commands

Besides lising zones and interfaces, you might be interested in services and ports:

# firewall-cmd --list-services
dhcpv6-client ssh
# firewall-cmd --list-ports

List used zones

The first only shows the zone names

# firewall-cmd --list-interfaces | xargs -I {} sh -c 'firewall-cmd --get-zone-of-interface={}'
public

The second both zones and interfaces:

# firewall-cmd --get-active-zones 
public
  interfaces: ens192

When there are no bound interfaces

OpenSuSE by default does not bind interfaces to zones; it means any interface uses the default zone. That means the --list-interfaces commands in this blog post fail.

You can check this behaviour by running this command:

# ls /sys/class/net | xargs -I {} sh -c 'echo -n "interface {} has zone " ; firewall-cmd --get-zone-of-interface={} | xargs -I [] sh -c "echo [] ; firewall-cmd --info-zone=[]"'
interface eth0 has zone no zone
interface lo has zone no zone
interface wlan0 has zone no zone

Alternatives:

  1. Finding the default zone
    # firewall-cmd --get-default-zone
    public
    
  2. Details of the default zone
    # firewall-cmd --info-zone=$(firewall-cmd --get-default-zone)
    public
      target: default
      icmp-block-inversion: no
      interfaces: 
      sources: 
      services: dhcpv6-client ssh
      ports: 
      protocols: 
      masquerade: no
      forward-ports: 
      source-ports: 
      icmp-blocks: 
      rich rules: 

You can see that here the public zone is marked default which means it binds to any interface that is not bound to a specific zone.

List used zone details

# firewall-cmd --list-interfaces | xargs -I {} sh -c 'firewall-cmd --get-zone-of-interface={} | xargs -I [] sh -c "firewall-cmd --info-zone=[]"'
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens192
  sources: 
  services: dhcpv6-client ssh
  ports: 
  protocols: 
  masquerade: no
  forward-ports: 
  source-ports: 
  icmp-blocks: 
  rich rules: 

List interfaces and their zones:

# firewall-cmd --list-interfaces | xargs -I {} sh -c 'echo -n "interface {} has zone " ; firewall-cmd --get-zone-of-interface={}'
interface ens192 has zone public

List interfaces and their zone details:

# firewall-cmd --list-interfaces | xargs -I {} sh -c 'echo -n "interface {} has zone " ; firewall-cmd --get-zone-of-interface={} | xargs -I [] sh -c "echo [] ; firewall-cmd --info-zone=[]"'
interface ens192 has zone public
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens192
  sources: 
  services: dhcpv6-client ssh
  ports: 
  protocols: 
  masquerade: no
  forward-ports: 
  source-ports: 
  icmp-blocks: 
  rich rules: 

Verifying if dns service is available, then allow it on public

Verify if a DNS is in the enabled services:

# firewall-cmd --list-services
dhcpv6-client ssh

Here no DNS service is enabled, so I need to figure out if any DNS service is available to be enabled.

This lists all the services that can be enabled in a zone:

# firewall-cmd --get-services

On my system, this returned the following list:

RH-Satellite-6 amanda-client amanda-k5-client amqp amqps apcupsd audit bacula bacula-client bb bgp bitcoin bitcoin-rpc bitcoin-testnet bitcoin-testnet-rpc bittorrent-lsd ceph ceph-mon cfengine cockpit condor-collector ctdb dhcp dhcpv6 dhcpv6-client distcc dns dns-over-tls docker-registry docker-swarm dropbox-lansync elasticsearch etcd-client etcd-server finger freeipa-4 freeipa-ldap freeipa-ldaps freeipa-replication freeipa-trust ftp ganglia-client ganglia-master git grafana gre http https imap imaps ipp ipp-client ipsec irc ircs iscsi-target isns jenkins kadmin kdeconnect kerberos kibana klogin kpasswd kprop kshell ldap ldaps libvirt libvirt-tls lightning-network llmnr managesieve matrix mdns memcache minidlna mongodb mosh mountd mqtt mqtt-tls ms-wbt mssql murmur mysql nfs nfs3 nmea-0183 nrpe ntp nut openvpn ovirt-imageio ovirt-storageconsole ovirt-vmconsole plex pmcd pmproxy pmwebapi pmwebapis pop3 pop3s postgresql privoxy prometheus proxy-dhcp ptp pulseaudio puppetmaster quassel radius rdp redis redis-sentinel rpc-bind rsh rsyncd rtsp salt-master samba samba-client samba-dc sane sip sips slp smtp smtp-submission smtps snmp snmptrap spideroak-lansync spotify-sync squid ssdp ssh steam-streaming svdrp svn syncthing syncthing-gui synergy syslog syslog-tls telnet tentacle tftp tftp-client tile38 tinc tor-socks transmission-client upnp-client vdsm vnc-server wbem-http wbem-https wsman wsmans xdmcp xmpp-bosh xmpp-client xmpp-local xmpp-server zabbix-agent zabbix-server

I was searching to see if dns was available, so I split the string with tr, then searced with grep:

# firewall-cmd --get-services | tr " " "\n" | grep dns
dns
dns-over-tls
mdns

To get details, use the firewall-cmd --info-service=servicename like this:

# firewall-cmd --get-services | tr " " "\n" | grep dns | xargs -I [] sh -c "firewall-cmd --info-service=[]"
dns
  ports: 53/tcp 53/udp
  protocols: 
  source-ports: 
  modules: 
  destination: 
  includes: 
dns-over-tls
  ports: 853/tcp
  protocols: 
  source-ports: 
  modules: 
  destination: 
  includes: 
mdns
  ports: 5353/udp
  protocols: 
  source-ports: 
  modules: 
  destination: ipv4:224.0.0.251 ipv6:ff02::fb
  includes: 

So for named (bind), I need the dns service to be enabled:

# firewall-cmd --zone=public --add-service=dns --permanent
success

Now a –list-services will not show dns as we changed the --permanent configuration, not the current configuration:

# firewall-cmd --list-services
dhcpv6-client ssh

So you need to --reload the --permanent settings:

# firewall-cmd --list-services --permanent
dhcpv6-client dns ssh
# firewall-cmd --reload
success
# firewall-cmd --list-services
dhcpv6-client dns ssh

–jeroen

Posted in *nix, *nix-tools, bash, bash, Development, iptables, Linux, openSuSE, Power User, Scripting, Software Development, SuSE Linux, Tumbleweed, xargs | Leave a Comment »

-r argument to pipe (no argument for MacOS)- If no input is given to xargs, don’t let xargs run the utility – Unix & Linux Stack Exchange

Posted by jpluimers on 2021/07/28

TL;DR

There is a non-standard -r option to xargs that allows it to skip executing when there are no arguments at all.

On some operating systems, the -r is default.

MacOS has no -r, but does not execute xargs if there are no arguments given.

Read the rest of this entry »

Posted in *nix, *nix-tools, bash, bash, Development, Power User, Scripting, Software Development, xargs | Leave a Comment »

VMware ESXi console: viewing all VMs, suspending and waking them up: part 2

Posted by jpluimers on 2021/04/27

Last week ended up to be a kind of VMware ESXi heavey, and this week will be similar. So it is time for following up on VMware ESXi console: viewing all VMs, suspending and waking them up: part 1.

That one ended with

Then we get this to print some of the capture groups:

vim-cmd vmsvc/getallvms | sed -n -E -e "s/^([[:digit:]]+)\s+((\S.+\S)?)\s+(\[\S+\])\s+(.+\.vmx)\s+(\S+)\s+(vmx-[[:digit:]]+)\s*?((\S.+)?)$/Vmid:\1 Guest:\6 Version:\7 Name:\3 Datastore:\4 File:\5 Annotation:\8/p"

With this output:

Vmid:10 Guest:windows9_64Guest Version:vmx-14 Name:X9SRI-3F-W10P-EN-MEDIA Datastore:[EVO860_500GB] File:VM/X9SRI-3F-W10P-EN-MEDIA/X9SRI-3F-W10P-EN-MEDIA.vmx Annotation:
Vmid:5 Guest:centos64Guest Version:vmx-11 Name:PPB Local_Virtual Machine_v4.0 Datastore:[EVO860_500GB] File:VM/PPB-Local_Virtual-Machine_v4.0/PPB Local_Virtual Machine_v4.0.vmx Annotation:PowerPanel Business software(Local) provides the service which communicates

Figuring out power state for each VM

This will be in the next installment, as by now this already has become a big blog-post (:

I basically went the vim-cmd vmsvc way instead of the esxcli vm way. My motivation was the easier to understand ID values. They are the basis of virtually all vim-cmd vmsvc based commands:

# vim-cmd vmsvc --help
Commands available under vmsvc/:
acquiremksticket                 get.snapshotinfo                 
acquireticket                    get.spaceNeededForConsolidation  
createdummyvm                    get.summary                      
destroy                          get.tasklist                     
device.connection                getallvms                        
device.connusbdev                gethostconstraints               
device.ctlradd                   message                          
device.ctlrremove                power.getstate                   
device.disconnusbdev             power.hibernate                  
device.diskadd                   power.off                        
device.diskaddexisting           power.on                         
device.diskextend                power.reboot                     
device.diskremove                power.reset                      
device.getdevices                power.shutdown                   
device.nvdimmadd                 power.suspend                    
device.nvdimmremove              power.suspendResume              
device.toolsSyncSet              queryftcompat                    
devices.createnic                reload                           
get.capability                   setscreenres                     
get.config                       snapshot.create                  
get.config.cpuidmask             snapshot.dumpoption              
get.configoption                 snapshot.get                     
get.datastores                   snapshot.remove                  
get.disabledmethods              snapshot.removeall               
get.environment                  snapshot.revert                  
get.filelayout                   snapshot.setoption               
get.filelayoutex                 tools.cancelinstall              
get.guest                        tools.install                    
get.guestheartbeatStatus         tools.upgrade                    
get.managedentitystatus          unregister                       
get.networks                     upgrade                          
get.runtime                      

My “goto” for getting information is [Wayback] “vim-cmd vmsvc” site:vmware.com – Google Search, and a few sample pages are here:

  1. [Wayback] Performing common virtual machine-related tasks with command-line utilities (2012964) (showing that there are many tasks only vim-cmd vmsvc can do, but esxcli vm cannot)
  2. [Wayback] Powering on a virtual machine from the command line when the host cannot be managed using vSphere Client (1038043) (showing how to combine vim-cmd vmsvc/getallvms, vim-cmd vmsvc/power.getstate and vim-cmd vmsvc/power.on)
  3. [Wayback] Determine the power status of a virtual machine on an ESX or ESXi host (1003737) (showing vim-cmd vmsvc/getallvms, vim-cmd vmsvc/power.getstate and ps –auxwww | grep –i VM_NAME)
  4. [Wayback] Collecting information about tasks in VMware ESXi/ESX (1013003) (showing the relation between VMs and tasks using  vim-cmd vimsvc/task_list, vim-cmd vmsvc/getallvms and vim-cmd vimsvc/task_info)
  5. [Wayback] Unable to Power off a Virtual Machine in an ESXi host (1014165) (focussing on vim-cmd vmsvc/getallvms, vim-cmd vmsvc/power.getstate, vim-cmd vmsvc/power.shutdown and vim-cmd vmsvc/power.off)
  6. [Wayback] Reloading a vmx file without removing the virtual machine from inventory (1026043) (showing vim-cmd vmsvc/getallvms and vim-cmd vmsvc/reload)
  7. [Wayback] Investigating virtual machine file locks on ESXi hosts (10051) (trying to show how to combine vim-cmd vmsvc/getallvms, grep, awk, find and xargs to find vmdk files, but fails because of parsing errors)

The pattern above is that most of the vim-cmd vmsvc examples are for power state and tasks. Not fully sure why, but my guess is it is what most people use it for. That kind of use what this series of posts also focuses on too, but certainly not the only use. Read the first numbered entry above to get a full grasp of what is possible. I hope to find time in the future to show some more examples outside the power and task realms.

Basically the only time you need to check out esxcli with VMs is when you cannot shut down a VM in a normal way. These links explain what to do in that case:

So let’s go back to basics, and start with getting info on all vim-cmd vmsvc commands.

Help on all vim-cmd vmsvc commands

Executing vim-cmd help vmsvc (preferred) or vim-cmd help vmsvc --help gives you all commands prepended with the line Commands available under vmsvc/:.

Executing vim-cmd help vmsvc/command prints the help for a single command (but vim-cmd help vmsvc/command -help first prints an error, then the help).

Here are the steps how I got the help help for all commands.

First I needed a list of all commands. This is already a multi-stage process, so below the full command I will explain the bits.

vim-cmd help vmsvc | sed '1d' | xargs -n 1 -r echo | sort
  1. vim-cmd help vmsvc gives all the commands (two per line!) prepended by the line Commands available under vmsvc/:.
  2. sed '1d' stripts that line.
  3. xargs -n 1 -r echo does a lot of things:
    1. It parses the sed '1d' input line by line, splits each line into parts, combines all the parts, then executes echo with the combined parts
    2. The -n 1 ensures each invocation of echo takes only a single one of the combined parts
    3. -r is just a protection: if there is no input, then echo is never executed, resulting in empty output
  4. sort will sort all the combined output of all the echo invocations to undo the horizontal combination of parts that xargs did

Now getting the help is doing more of the above, with some more bits to explain:

vim-cmd help vmsvc | sed '1d' | xargs -n 1 -r echo | sort | xargs -n 1 -r -I {} vim-cmd help vmsvc/{}
  1. Normally, xargs will execute each command by appending the parameter inserting a space in front of each parameter
  2. -I {} will force xargs to put each argument just as is in the place where {} is used in the argument
  3. This executes vim-cmd help vmsvc/command in stead of vim-cmd help vmsvc/ command

The result is a long blob of text that is very hard to read as there are no separators between the commands. I saved it as a [Wayback] vim-cmd help for each vmsvc command.txt gist.

With a sh -c shell trick, you can add some more information and separation to the output by embedding :

vim-cmd help vmsvc | sed '1d' | xargs -n 1 -r echo | sort | xargs -n 1 -r -I {} sh -c 'echo "-----" ; echo "help for vim-cmd help vmsvc/{}" ; echo ; vim-cmd help vmsvc/{}'

I have added the output to the [Wayback] delimited vim-cmd help for each vmsvc command.txt gist.

Commands taking a vmid parameter

Now that we know how to output all help, we can filter on it.

An interesting one is to filder only commands taking a vmid parameter:

vim-cmd help vmsvc | sed '1d' | xargs -n 1 -r echo | sort | xargs -n 1 -r -I {} vim-cmd help vmsvc/{} | grep -iw vmid

On VMware ESXi 6.7, this gets you the list:

Usage: acquiremksticket vmid
Usage: acquireticket vmid ticketType
Usage: destroy vmid
Usage: device.connection vmid deviceKey connect
Usage: device.connusbdev vmid usbid
Usage: device.ctlradd vmid ctlr_type bus_number
Usage: device.ctlrremove vmid ctlr_type bus_number
Usage: device.disconnusbdev vmid usbid
Usage: device.diskadd vmid size controller_numer unit_number datastore [ctlr_type]
Usage: device.diskaddexisting vmid disk_file controller_number unit_number [ctlr_type]
Usage: device.diskextend vmid new_size controller_numer unit_number [ctlr_type]
Usage: device.diskremove vmid controller_number unit_number delete_file [controller_type]
Usage: device.getdevices vmid
Usage: device.nvdimmadd vmid size
Usage: device.nvdimmremove vmid deviceKey
Usage: device.toolsSyncSet vmid new state
Usage: devices.createnic vmid adapter-type network-id [network-type]
Usage: get.capability vmid
Usage: get.config vmid
Usage: get.config.cpuidmask vmid
Usage: get.configoption vmid
Usage: get.datastores vmid
Usage: get.disabledmethods vmid
Usage: get.environment vmid
Usage: get.filelayout vmid
Usage: get.filelayoutex vmid
Usage: get.guest vmid
Usage: get.guestheartbeatStatus vmid
Usage: get.managedentitystatus vmid
Usage: get.networks vmid
Usage: get.runtime vmid
Usage: get.snapshotinfo vmid
Usage: get.spaceNeededForConsolidation vmid
Usage: get.summary vmid
Usage: get.tasklist vmid
Usage: message vmid [messageId] [messageChoice]
Usage: power.getstate vmid
Usage: power.hibernate vmid
Usage: power.off vmid
Usage: power.on vmid
Usage: power.reboot vmid
Usage: power.reset vmid
Usage: power.shutdown vmid
Usage: power.suspend vmid
Usage: power.suspendResume vmid
Usage: queryftcompat vmid [faultToleranceType]
Usage: reload vmid
Usage: setscreenres vmid width height
Usage: snapshot.create vmid [snapshotName] [snapshotDescription] [includeMemory] [quiesced]
Usage: snapshot.get vmid
Usage: snapshot.remove vmid snapshotId [removeChildren]
Usage: snapshot.removeall vmid
Usage: snapshot.revert vmid snapshotId suppressPowerOn
Usage: snapshot.setoption [OPTIONS] vmid
Usage: tools.cancelinstall vmid
Usage: tools.install vmid
Usage: tools.upgrade vmid [args]
Usage: unregister vmid
Usage: upgrade vmid [vm_hwversion]

In the above list, the bold entries have to do with power, that is what this series is supposed to center around, so more on that tomorrow.

–jeroen

Posted in *nix, *nix-tools, ash/dash, ash/dash development, Awk, Development, ESXi6, ESXi6.5, ESXi6.7, ESXi7, fgrep, Power User, Scripting, sed, sed script, sh, Sh Shell, Software Development, sort, Virtualization, VMware, VMware ESXi, xargs | Leave a Comment »

 
%d bloggers like this: