Initial release
This commit is contained in:
parent
84ccf6afda
commit
c07eeea3ab
7
csv2glpi/go.mod
Normal file
7
csv2glpi/go.mod
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
module importer
|
||||||
|
|
||||||
|
go 1.16
|
||||||
|
|
||||||
|
replace glpi => ../glpi
|
||||||
|
|
||||||
|
require glpi v0.0.0-00010101000000-000000000000 // indirect
|
172
csv2glpi/importer.go
Normal file
172
csv2glpi/importer.go
Normal file
|
@ -0,0 +1,172 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/csv"
|
||||||
|
"strings"
|
||||||
|
// "encoding/json"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"glpi"
|
||||||
|
"os"
|
||||||
|
"reflect"
|
||||||
|
"strconv"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
glpiServerAPI string
|
||||||
|
glpiUserToken string
|
||||||
|
glpiAppToken string
|
||||||
|
glpiAssetsType string
|
||||||
|
glpiVersion bool
|
||||||
|
operation string
|
||||||
|
inFileName string
|
||||||
|
inFormat string
|
||||||
|
inCSVSeparator string
|
||||||
|
inCSVComment string
|
||||||
|
outFileName string
|
||||||
|
outFormat string
|
||||||
|
outCSVSeparator string
|
||||||
|
outCSVComment string
|
||||||
|
)
|
||||||
|
|
||||||
|
func CSVToGLPI(glpiAPI *glpi.Session, fileName string) {
|
||||||
|
file, err := os.Open(fileName)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
reader := csv.NewReader(file)
|
||||||
|
reader.Comment, _ = utf8.DecodeRuneInString(inCSVComment)
|
||||||
|
reader.Comma, _ = utf8.DecodeRuneInString(inCSVSeparator)
|
||||||
|
reader.TrimLeadingSpace = true
|
||||||
|
|
||||||
|
headers, err := reader.Read()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
record, err := reader.Read()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
fmt.Println(record)
|
||||||
|
var (
|
||||||
|
recordMap glpi.GlpiPhone
|
||||||
|
)
|
||||||
|
|
||||||
|
// recordMap.Name = "test"
|
||||||
|
// Read the headers and find field name in structure
|
||||||
|
for fieldIndex, fieldName := range headers {
|
||||||
|
s := reflect.ValueOf(&recordMap).Elem()
|
||||||
|
typeOfT := s.Type()
|
||||||
|
for i := 0; i < s.NumField(); i++ {
|
||||||
|
// if the field is found in the structure, we assign it a value of the appropriate type
|
||||||
|
if strings.EqualFold(strings.ToLower(fieldName), strings.ToLower(typeOfT.Field(i).Name)) {
|
||||||
|
switch fmt.Sprint(typeOfT.Field(i).Type) {
|
||||||
|
case "int":
|
||||||
|
convValue, _ := strconv.Atoi(record[fieldIndex])
|
||||||
|
s.Field(i).SetInt(int64(convValue))
|
||||||
|
case "string":
|
||||||
|
s.Field(i).SetString(record[fieldIndex])
|
||||||
|
case "bool":
|
||||||
|
convValue, _ := strconv.ParseBool(record[fieldIndex])
|
||||||
|
s.Field(i).SetBool(convValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// fmt.Println(recordMap)
|
||||||
|
fmt.Println("Added", glpiAssetsType, "with ID:", glpiAPI.ItemOperation("add", glpiAssetsType, recordMap))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExportFromGLPI(glpiAPI *glpi.Session, fileName string) {
|
||||||
|
fmt.Println(fileName)
|
||||||
|
// file, err := os.Open(fileName)
|
||||||
|
// if err != nil {
|
||||||
|
// panic(err)
|
||||||
|
// }
|
||||||
|
// defer file.Close()
|
||||||
|
|
||||||
|
// reader := csv.NewReader(file)
|
||||||
|
// reader.Comma = outCSVSeparator
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
|
||||||
|
flag.StringVar(&glpiServerAPI, "glpi-server-api", "", "Glpi instance API URL. GLPI_SERVER_URL")
|
||||||
|
flag.StringVar(&glpiUserToken, "glpi-user-token", "", "Glpi user API token. GLPI_USER_TOKEN")
|
||||||
|
flag.StringVar(&glpiAppToken, "glpi-app-token", "", "Glpi aplication API token. GLPI_APP_TOKEN")
|
||||||
|
flag.StringVar(&glpiAssetsType, "glpi-assets-type", "", "Glpi assets type (aka Computer, Printer, Phone, e.t.c.)")
|
||||||
|
flag.BoolVar(&glpiVersion, "glpi-version", false, "Get the Glpi version")
|
||||||
|
|
||||||
|
flag.StringVar(&operation, "operation", "", "import - import data to GLPI from file\n\texport - export data from GLPI to file\n\t")
|
||||||
|
|
||||||
|
flag.StringVar(&inFileName, "in-file", "", "the name of the file containing the imported data")
|
||||||
|
flag.StringVar(&inFormat, "in-format", "csv", "input file data format")
|
||||||
|
flag.StringVar(&inCSVSeparator, "in-csv-separator", ";", "input csv-file separator")
|
||||||
|
flag.StringVar(&inCSVComment, "in-csv-comment", "#", "input csv-file comments symbol")
|
||||||
|
|
||||||
|
flag.StringVar(&outFileName, "out-file", "", "the name of the file containing the exported data")
|
||||||
|
flag.StringVar(&outFormat, "out-format", "json", "Output format: 'go' - go map, 'json' - json string, 'csv' - common separated value")
|
||||||
|
flag.StringVar(&outCSVSeparator, "out-csv-separator", ";", "output csv-file separator")
|
||||||
|
flag.StringVar(&outCSVComment, "out-csv-comment", "#", "output csv-file comments symbol")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
//-----------------------------------------------------------
|
||||||
|
if glpiServerAPI == "" && os.Getenv("GLPI_SERVER_API") == "" {
|
||||||
|
fmt.Println("Send error: make sure environment variables `GLPI_SERVER_API`, or used with '-glpi-server-api' argument")
|
||||||
|
os.Exit(1)
|
||||||
|
} else if glpiServerAPI == "" && os.Getenv("GLPI_SERVER_API") != "" {
|
||||||
|
glpiServerAPI = os.Getenv("GLPI_SERVER_API")
|
||||||
|
}
|
||||||
|
|
||||||
|
if glpiUserToken == "" && os.Getenv("GLPI_USER_TOKEN") == "" {
|
||||||
|
fmt.Println("Send error: make sure environment variables `GLPI_USER_TOKEN`, or used with '-glpi-user-token' argument")
|
||||||
|
os.Exit(1)
|
||||||
|
} else if glpiUserToken == "" && os.Getenv("GLPI_USER_TOKEN") != "" {
|
||||||
|
glpiUserToken = os.Getenv("GLPI_USER_TOKEN")
|
||||||
|
}
|
||||||
|
|
||||||
|
if glpiAppToken == "" && os.Getenv("GLPI_APP_TOKEN") == "" {
|
||||||
|
fmt.Println("Send error: make sure environment variables `GLPI_APP_TOKEN`, or used with '-glpi-app-token' argument")
|
||||||
|
os.Exit(1)
|
||||||
|
} else if glpiAppToken == "" && os.Getenv("GLPI_APP_TOKEN") != "" {
|
||||||
|
glpiAppToken = os.Getenv("GLPI_APP_TOKEN")
|
||||||
|
}
|
||||||
|
|
||||||
|
glpiSession, err := glpi.NewSession(glpiServerAPI, glpiUserToken, glpiAppToken)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, err = glpiSession.InitSession()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if glpiVersion {
|
||||||
|
fmt.Println("GLPI version:", glpiSession.Version())
|
||||||
|
}
|
||||||
|
|
||||||
|
switch operation {
|
||||||
|
case "import":
|
||||||
|
if inFileName == "" || glpiAssetsType == "" {
|
||||||
|
fmt.Println("Setting the input file name and glpi assets type, use the '-in-file' and '-glpi-assets-type' argument")
|
||||||
|
} else {
|
||||||
|
CSVToGLPI(glpiSession, inFileName)
|
||||||
|
}
|
||||||
|
case "export":
|
||||||
|
if outFileName == "" {
|
||||||
|
fmt.Println("Setting the output file name, use the '-out-file' argument")
|
||||||
|
} else {
|
||||||
|
ExportFromGLPI(glpiSession, outFileName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
glpiSession.KillSession()
|
||||||
|
}
|
339
glpi/LICENSE
Normal file
339
glpi/LICENSE
Normal file
|
@ -0,0 +1,339 @@
|
||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 2, June 1991
|
||||||
|
|
||||||
|
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
|
||||||
|
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The licenses for most software are designed to take away your
|
||||||
|
freedom to share and change it. By contrast, the GNU General Public
|
||||||
|
License is intended to guarantee your freedom to share and change free
|
||||||
|
software--to make sure the software is free for all its users. This
|
||||||
|
General Public License applies to most of the Free Software
|
||||||
|
Foundation's software and to any other program whose authors commit to
|
||||||
|
using it. (Some other Free Software Foundation software is covered by
|
||||||
|
the GNU Lesser General Public License instead.) You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
this service if you wish), that you receive source code or can get it
|
||||||
|
if you want it, that you can change the software or use pieces of it
|
||||||
|
in new free programs; and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to make restrictions that forbid
|
||||||
|
anyone to deny you these rights or to ask you to surrender the rights.
|
||||||
|
These restrictions translate to certain responsibilities for you if you
|
||||||
|
distribute copies of the software, or if you modify it.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must give the recipients all the rights that
|
||||||
|
you have. You must make sure that they, too, receive or can get the
|
||||||
|
source code. And you must show them these terms so they know their
|
||||||
|
rights.
|
||||||
|
|
||||||
|
We protect your rights with two steps: (1) copyright the software, and
|
||||||
|
(2) offer you this license which gives you legal permission to copy,
|
||||||
|
distribute and/or modify the software.
|
||||||
|
|
||||||
|
Also, for each author's protection and ours, we want to make certain
|
||||||
|
that everyone understands that there is no warranty for this free
|
||||||
|
software. If the software is modified by someone else and passed on, we
|
||||||
|
want its recipients to know that what they have is not the original, so
|
||||||
|
that any problems introduced by others will not reflect on the original
|
||||||
|
authors' reputations.
|
||||||
|
|
||||||
|
Finally, any free program is threatened constantly by software
|
||||||
|
patents. We wish to avoid the danger that redistributors of a free
|
||||||
|
program will individually obtain patent licenses, in effect making the
|
||||||
|
program proprietary. To prevent this, we have made it clear that any
|
||||||
|
patent must be licensed for everyone's free use or not licensed at all.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||||
|
|
||||||
|
0. This License applies to any program or other work which contains
|
||||||
|
a notice placed by the copyright holder saying it may be distributed
|
||||||
|
under the terms of this General Public License. The "Program", below,
|
||||||
|
refers to any such program or work, and a "work based on the Program"
|
||||||
|
means either the Program or any derivative work under copyright law:
|
||||||
|
that is to say, a work containing the Program or a portion of it,
|
||||||
|
either verbatim or with modifications and/or translated into another
|
||||||
|
language. (Hereinafter, translation is included without limitation in
|
||||||
|
the term "modification".) Each licensee is addressed as "you".
|
||||||
|
|
||||||
|
Activities other than copying, distribution and modification are not
|
||||||
|
covered by this License; they are outside its scope. The act of
|
||||||
|
running the Program is not restricted, and the output from the Program
|
||||||
|
is covered only if its contents constitute a work based on the
|
||||||
|
Program (independent of having been made by running the Program).
|
||||||
|
Whether that is true depends on what the Program does.
|
||||||
|
|
||||||
|
1. You may copy and distribute verbatim copies of the Program's
|
||||||
|
source code as you receive it, in any medium, provided that you
|
||||||
|
conspicuously and appropriately publish on each copy an appropriate
|
||||||
|
copyright notice and disclaimer of warranty; keep intact all the
|
||||||
|
notices that refer to this License and to the absence of any warranty;
|
||||||
|
and give any other recipients of the Program a copy of this License
|
||||||
|
along with the Program.
|
||||||
|
|
||||||
|
You may charge a fee for the physical act of transferring a copy, and
|
||||||
|
you may at your option offer warranty protection in exchange for a fee.
|
||||||
|
|
||||||
|
2. You may modify your copy or copies of the Program or any portion
|
||||||
|
of it, thus forming a work based on the Program, and copy and
|
||||||
|
distribute such modifications or work under the terms of Section 1
|
||||||
|
above, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) You must cause the modified files to carry prominent notices
|
||||||
|
stating that you changed the files and the date of any change.
|
||||||
|
|
||||||
|
b) You must cause any work that you distribute or publish, that in
|
||||||
|
whole or in part contains or is derived from the Program or any
|
||||||
|
part thereof, to be licensed as a whole at no charge to all third
|
||||||
|
parties under the terms of this License.
|
||||||
|
|
||||||
|
c) If the modified program normally reads commands interactively
|
||||||
|
when run, you must cause it, when started running for such
|
||||||
|
interactive use in the most ordinary way, to print or display an
|
||||||
|
announcement including an appropriate copyright notice and a
|
||||||
|
notice that there is no warranty (or else, saying that you provide
|
||||||
|
a warranty) and that users may redistribute the program under
|
||||||
|
these conditions, and telling the user how to view a copy of this
|
||||||
|
License. (Exception: if the Program itself is interactive but
|
||||||
|
does not normally print such an announcement, your work based on
|
||||||
|
the Program is not required to print an announcement.)
|
||||||
|
|
||||||
|
These requirements apply to the modified work as a whole. If
|
||||||
|
identifiable sections of that work are not derived from the Program,
|
||||||
|
and can be reasonably considered independent and separate works in
|
||||||
|
themselves, then this License, and its terms, do not apply to those
|
||||||
|
sections when you distribute them as separate works. But when you
|
||||||
|
distribute the same sections as part of a whole which is a work based
|
||||||
|
on the Program, the distribution of the whole must be on the terms of
|
||||||
|
this License, whose permissions for other licensees extend to the
|
||||||
|
entire whole, and thus to each and every part regardless of who wrote it.
|
||||||
|
|
||||||
|
Thus, it is not the intent of this section to claim rights or contest
|
||||||
|
your rights to work written entirely by you; rather, the intent is to
|
||||||
|
exercise the right to control the distribution of derivative or
|
||||||
|
collective works based on the Program.
|
||||||
|
|
||||||
|
In addition, mere aggregation of another work not based on the Program
|
||||||
|
with the Program (or with a work based on the Program) on a volume of
|
||||||
|
a storage or distribution medium does not bring the other work under
|
||||||
|
the scope of this License.
|
||||||
|
|
||||||
|
3. You may copy and distribute the Program (or a work based on it,
|
||||||
|
under Section 2) in object code or executable form under the terms of
|
||||||
|
Sections 1 and 2 above provided that you also do one of the following:
|
||||||
|
|
||||||
|
a) Accompany it with the complete corresponding machine-readable
|
||||||
|
source code, which must be distributed under the terms of Sections
|
||||||
|
1 and 2 above on a medium customarily used for software interchange; or,
|
||||||
|
|
||||||
|
b) Accompany it with a written offer, valid for at least three
|
||||||
|
years, to give any third party, for a charge no more than your
|
||||||
|
cost of physically performing source distribution, a complete
|
||||||
|
machine-readable copy of the corresponding source code, to be
|
||||||
|
distributed under the terms of Sections 1 and 2 above on a medium
|
||||||
|
customarily used for software interchange; or,
|
||||||
|
|
||||||
|
c) Accompany it with the information you received as to the offer
|
||||||
|
to distribute corresponding source code. (This alternative is
|
||||||
|
allowed only for noncommercial distribution and only if you
|
||||||
|
received the program in object code or executable form with such
|
||||||
|
an offer, in accord with Subsection b above.)
|
||||||
|
|
||||||
|
The source code for a work means the preferred form of the work for
|
||||||
|
making modifications to it. For an executable work, complete source
|
||||||
|
code means all the source code for all modules it contains, plus any
|
||||||
|
associated interface definition files, plus the scripts used to
|
||||||
|
control compilation and installation of the executable. However, as a
|
||||||
|
special exception, the source code distributed need not include
|
||||||
|
anything that is normally distributed (in either source or binary
|
||||||
|
form) with the major components (compiler, kernel, and so on) of the
|
||||||
|
operating system on which the executable runs, unless that component
|
||||||
|
itself accompanies the executable.
|
||||||
|
|
||||||
|
If distribution of executable or object code is made by offering
|
||||||
|
access to copy from a designated place, then offering equivalent
|
||||||
|
access to copy the source code from the same place counts as
|
||||||
|
distribution of the source code, even though third parties are not
|
||||||
|
compelled to copy the source along with the object code.
|
||||||
|
|
||||||
|
4. You may not copy, modify, sublicense, or distribute the Program
|
||||||
|
except as expressly provided under this License. Any attempt
|
||||||
|
otherwise to copy, modify, sublicense or distribute the Program is
|
||||||
|
void, and will automatically terminate your rights under this License.
|
||||||
|
However, parties who have received copies, or rights, from you under
|
||||||
|
this License will not have their licenses terminated so long as such
|
||||||
|
parties remain in full compliance.
|
||||||
|
|
||||||
|
5. You are not required to accept this License, since you have not
|
||||||
|
signed it. However, nothing else grants you permission to modify or
|
||||||
|
distribute the Program or its derivative works. These actions are
|
||||||
|
prohibited by law if you do not accept this License. Therefore, by
|
||||||
|
modifying or distributing the Program (or any work based on the
|
||||||
|
Program), you indicate your acceptance of this License to do so, and
|
||||||
|
all its terms and conditions for copying, distributing or modifying
|
||||||
|
the Program or works based on it.
|
||||||
|
|
||||||
|
6. Each time you redistribute the Program (or any work based on the
|
||||||
|
Program), the recipient automatically receives a license from the
|
||||||
|
original licensor to copy, distribute or modify the Program subject to
|
||||||
|
these terms and conditions. You may not impose any further
|
||||||
|
restrictions on the recipients' exercise of the rights granted herein.
|
||||||
|
You are not responsible for enforcing compliance by third parties to
|
||||||
|
this License.
|
||||||
|
|
||||||
|
7. If, as a consequence of a court judgment or allegation of patent
|
||||||
|
infringement or for any other reason (not limited to patent issues),
|
||||||
|
conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot
|
||||||
|
distribute so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you
|
||||||
|
may not distribute the Program at all. For example, if a patent
|
||||||
|
license would not permit royalty-free redistribution of the Program by
|
||||||
|
all those who receive copies directly or indirectly through you, then
|
||||||
|
the only way you could satisfy both it and this License would be to
|
||||||
|
refrain entirely from distribution of the Program.
|
||||||
|
|
||||||
|
If any portion of this section is held invalid or unenforceable under
|
||||||
|
any particular circumstance, the balance of the section is intended to
|
||||||
|
apply and the section as a whole is intended to apply in other
|
||||||
|
circumstances.
|
||||||
|
|
||||||
|
It is not the purpose of this section to induce you to infringe any
|
||||||
|
patents or other property right claims or to contest validity of any
|
||||||
|
such claims; this section has the sole purpose of protecting the
|
||||||
|
integrity of the free software distribution system, which is
|
||||||
|
implemented by public license practices. Many people have made
|
||||||
|
generous contributions to the wide range of software distributed
|
||||||
|
through that system in reliance on consistent application of that
|
||||||
|
system; it is up to the author/donor to decide if he or she is willing
|
||||||
|
to distribute software through any other system and a licensee cannot
|
||||||
|
impose that choice.
|
||||||
|
|
||||||
|
This section is intended to make thoroughly clear what is believed to
|
||||||
|
be a consequence of the rest of this License.
|
||||||
|
|
||||||
|
8. If the distribution and/or use of the Program is restricted in
|
||||||
|
certain countries either by patents or by copyrighted interfaces, the
|
||||||
|
original copyright holder who places the Program under this License
|
||||||
|
may add an explicit geographical distribution limitation excluding
|
||||||
|
those countries, so that distribution is permitted only in or among
|
||||||
|
countries not thus excluded. In such case, this License incorporates
|
||||||
|
the limitation as if written in the body of this License.
|
||||||
|
|
||||||
|
9. The Free Software Foundation may publish revised and/or new versions
|
||||||
|
of the General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the Program
|
||||||
|
specifies a version number of this License which applies to it and "any
|
||||||
|
later version", you have the option of following the terms and conditions
|
||||||
|
either of that version or of any later version published by the Free
|
||||||
|
Software Foundation. If the Program does not specify a version number of
|
||||||
|
this License, you may choose any version ever published by the Free Software
|
||||||
|
Foundation.
|
||||||
|
|
||||||
|
10. If you wish to incorporate parts of the Program into other free
|
||||||
|
programs whose distribution conditions are different, write to the author
|
||||||
|
to ask for permission. For software which is copyrighted by the Free
|
||||||
|
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||||
|
make exceptions for this. Our decision will be guided by the two goals
|
||||||
|
of preserving the free status of all derivatives of our free software and
|
||||||
|
of promoting the sharing and reuse of software generally.
|
||||||
|
|
||||||
|
NO WARRANTY
|
||||||
|
|
||||||
|
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||||
|
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||||
|
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||||
|
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||||
|
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||||
|
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||||
|
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||||
|
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||||
|
REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||||
|
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||||
|
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||||
|
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||||
|
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||||
|
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||||
|
POSSIBILITY OF SUCH DAMAGES.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
convey the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
{description}
|
||||||
|
Copyright (C) {year} {fullname}
|
||||||
|
|
||||||
|
This program is free software; you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation; either version 2 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License along
|
||||||
|
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||||
|
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program is interactive, make it output a short notice like this
|
||||||
|
when it starts in an interactive mode:
|
||||||
|
|
||||||
|
Gnomovision version 69, Copyright (C) year name of author
|
||||||
|
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, the commands you use may
|
||||||
|
be called something other than `show w' and `show c'; they could even be
|
||||||
|
mouse-clicks or menu items--whatever suits your program.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or your
|
||||||
|
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||||
|
necessary. Here is a sample; alter the names:
|
||||||
|
|
||||||
|
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||||
|
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||||
|
|
||||||
|
{signature of Ty Coon}, 1 April 1989
|
||||||
|
Ty Coon, President of Vice
|
||||||
|
|
||||||
|
This General Public License does not permit incorporating your program into
|
||||||
|
proprietary programs. If your program is a subroutine library, you may
|
||||||
|
consider it more useful to permit linking proprietary applications with the
|
||||||
|
library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License.
|
398
glpi/README-ru.md
Normal file
398
glpi/README-ru.md
Normal file
|
@ -0,0 +1,398 @@
|
||||||
|
Данный модуль для языка GO реализует механизм работы с HTTP API системы GLPI. Описание АПИ доступно по адресу https://github.com/glpi-project/glpi/blob/9.5/bugfixes/apirest.md, и также в установленной системе по ссылке https://glpi/apirest.php .
|
||||||
|
|
||||||
|
Ниже представлен вариант использования на примере работы с принтером. Т.е. в примере будет выполнено:
|
||||||
|
- Добавление производителя
|
||||||
|
- Добавление модели принтера
|
||||||
|
- Добавление домена
|
||||||
|
- Добавление сети (виртуальная сущность связывающаяя активы на сетевом уровне)
|
||||||
|
- Добавление принтера
|
||||||
|
- Добавление сетевого порта и привязка его к принтеру
|
||||||
|
- Добавление IP-адреса и привязка его к порту
|
||||||
|
- Добавление модели картриджа
|
||||||
|
- Добавление картриджа как еденицы учета
|
||||||
|
- "Установка" картриджа (привязка его к соответствующему принтеру)
|
||||||
|
|
||||||
|
Алгоритм работы с активами и другими сущностями GLPI ничем не отличается от данного примера.
|
||||||
|
|
||||||
|
# Краткое описание API
|
||||||
|
|
||||||
|
## Инициализация сессии
|
||||||
|
|
||||||
|
Работа с API в GLPI производится в рамках сессии, которая определяется на основе кода доступа (токена). Данный код генерится и возвращается после положительной авторизации пользователя. Для этого требуется выполнить HTTP запрос к API методу "initSession" и передать в нём Application токен ("Настройки" -> "Общие" -> "API") и токен пользователя ("Администрирование" -> "Пользователи" -> Пользователь -> "Ключи Удаленного доступа") либо имя и пароль.
|
||||||
|
|
||||||
|
```curl -s -X GET -H "Content-Type: application/json" -H "Authorization: user_token ${GLPI_USER_TOKEN}" -H "App-Token: ${GLPI_APP_TOKEN}" "https://glpi/apirest.php/initSession"```
|
||||||
|
|
||||||
|
При положительном ответе система вернет:
|
||||||
|
|
||||||
|
```
|
||||||
|
{
|
||||||
|
"session_token": "6ud8p3llbvl4qkf56t7klvhvr"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
В дальнейшем в запросах передается токен приложения и токен сессии:
|
||||||
|
|
||||||
|
```curl -s -X GET -H "Content-Type: application/json" -H "Session-Token: ${GLPI_SESSION_TOKEN}" -H "App-Token: ${GLPI_APP_TOKEN}" "https://glpi/apirest.php/passivedcequipment"```
|
||||||
|
|
||||||
|
## Получение данных из GLPI
|
||||||
|
|
||||||
|
Для получения данных необходимо выполнить http-запрос к определенному методу API. Например для вывода информации о всех компьютерах ссылка будет выглядеть вот так:
|
||||||
|
|
||||||
|
```"https://glpi/apirest.php/computer"```
|
||||||
|
|
||||||
|
для получения данных по конкретному компьютеру:
|
||||||
|
|
||||||
|
```"https://glpi/apirest.php/computer/123"```
|
||||||
|
|
||||||
|
|
||||||
|
где "computer" - это тип актива (сущности, еденицы учета и т.п.), "123" - это уникальный идентификатор записи.
|
||||||
|
|
||||||
|
# Пример использования go-модуля glpi
|
||||||
|
|
||||||
|
## Импорт пакетов
|
||||||
|
|
||||||
|
``` go
|
||||||
|
package main
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"glpi"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Установка переменных
|
||||||
|
Объявляем и инициализируем переменные:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
var (
|
||||||
|
glpiServerAPI string
|
||||||
|
glpiUserToken string
|
||||||
|
glpiAppToken string
|
||||||
|
)
|
||||||
|
glpiServerAPI = os.Getenv("GLPI_SERVER_API")
|
||||||
|
glpiUserToken = os.Getenv("GLPI_USER_TOKEN")
|
||||||
|
glpiAppToken = os.Getenv("GLPI_APP_TOKEN")
|
||||||
|
```
|
||||||
|
|
||||||
|
* glpiServerAPI - адрес вызова API, в нашем случае берется из переменной окружения и равен https://glpi/apirest.php
|
||||||
|
* glpiUserToken - код доступа к API GLPI для конкретного пользователя
|
||||||
|
* glpiAppToken - код доступа к API GLPI
|
||||||
|
|
||||||
|
Для удобства работы, значения для данных переменных, беруться из переменных окружения.
|
||||||
|
|
||||||
|
Так как для начала работы необходимо получить код доступа для конкретной сессии, то произведем инициализацию сессиии:
|
||||||
|
``` go
|
||||||
|
glpiSession, err := glpi.NewSession(glpiServerAPI, glpiUserToken, glpiAppToken)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
```
|
||||||
|
glpi.NewSession - создает переменную типа Session и возвращает указатель на нее.
|
||||||
|
|
||||||
|
``` go
|
||||||
|
_, err = glpiSession.InitSession()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
```
|
||||||
|
glpiSession.InitSession() - инициализирует сессию, т.е. при вызове данной функции, происходит подключение к GLPI API и возвращается значение кода доступа (токена)сессии. Его значение сохраняется в поле структуры "glpiSession.sessionToken". Данный код можно посмотреть вызвав функцию "glpiSession.GetSessionToken()", т.е.
|
||||||
|
|
||||||
|
```fmt.Println(glpiSession.GetSessionToken())```
|
||||||
|
|
||||||
|
Установим значения некоторых переменных:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
itemType := "Printer"
|
||||||
|
printerName := "acc-prn1"
|
||||||
|
printerDomain := "domain.local"
|
||||||
|
```
|
||||||
|
|
||||||
|
В GLPI API для поиска данных реализован метод search, вызываемый по ссылке http://glpi/apirest.php/search/itemtype/, где itemtype это тип еденицы учета либо другой сущности внутри GLPI (computer, monitor, printer, line и так далее).
|
||||||
|
|
||||||
|
В модуле glpi для поиска используется функция "SearchItem(itemType string, itemName string)" вызываемая с параметрами:
|
||||||
|
|
||||||
|
- itemType - вышеозначенный тип
|
||||||
|
- itemName - имя.
|
||||||
|
|
||||||
|
В случае положительного результата функция возвращает цифровой уникальный идентификатор записи "ID".
|
||||||
|
|
||||||
|
Тут стоит остановиться подробнее на описании структуры и типах. В GO-модуле glpi каждая из сущностей представлена ввиде структуры с соответсвующим именем. Внтури структуры описано соответствие её полей и полей в итоговом JSON запросе. Например для производителей:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
type GlpiManufacturer struct {
|
||||||
|
Id int `json:"id"`
|
||||||
|
Comment string `json:"comment"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Имена и типы полей go-структуры соответсвуют именам и типам таковых в JSON, кроме первой буквы (в json она маленькая).
|
||||||
|
|
||||||
|
Для операций с записями в модуле реализованы функции с именами соответствующими glpi-типам (кроме простых типов с одинаковой струкрутрой). Функция на вход принимает тип запроса ("add" - добавление записи, "update" - редактирование, "delete" -удаление) и структуру соответствующего типа.
|
||||||
|
|
||||||
|
Т.е. для производителей это будет glpiSession.Manufacturer("add", manufacturersData) для принтеров glpiSession.Printer("add", printerData) и так далее.
|
||||||
|
|
||||||
|
Для простых типов введена структура:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
type GlpiSimpleItem struct {
|
||||||
|
Id int `json:"id"`
|
||||||
|
Comment string `json:"comment"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Для моделей оборудования различного типа:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
type GlpiItemModel struct {
|
||||||
|
Id int `json:"id"`
|
||||||
|
Comment string `json:"comment"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Product_number string `json:"product_number"`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
И соответсвенно им и функции SimpleItem() и ItemModel().
|
||||||
|
|
||||||
|
В данном примере произведем поиск производителя по наименованию, и если записи с таким именем не найдено то добавим её.
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// Get manufacturer ID or append new records/
|
||||||
|
manufacturersID := glpiSession.SearchItem("Manufacturer", "Systers")
|
||||||
|
if manufacturersID == 0 {
|
||||||
|
manufacturersData := glpi.GlpiManufacturer{
|
||||||
|
Name: "Systers",
|
||||||
|
Comment: "Holly Systers inc.",
|
||||||
|
}
|
||||||
|
manufacturersID = glpiSession.ItemOperation("add", "Manufacturer", manufacturersData)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Т.е. если manufacturersID будет равен 0 то инициализируем переменную типа GlpiManufacturer, заполним поля требуемыми значениями и вызовем нужную функцию. На выходе получим ID производителя для дальнейшего использования.
|
||||||
|
|
||||||
|
Найдем или добавим сеть (в данном контексте "сеть" - используется для объединения активов и построения схемы сети):
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// Get network ID or append new records/
|
||||||
|
networksID := glpiSession.SearchItem("Network", "Head office")
|
||||||
|
if networksID == 0 {
|
||||||
|
networksData := glpi.GlpiSimpleItem{
|
||||||
|
Name: "Head office",
|
||||||
|
Comment: "Head office network",
|
||||||
|
}
|
||||||
|
networksID = glpiSession.ItemOperation("add", "Network", networksData)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Модель принтера:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// Search a used printer model, or append if don't find it.
|
||||||
|
printerModelID := glpiSession.SearchItem("PrinterModel", "Sys 1200")
|
||||||
|
if printerModelID == 0 {
|
||||||
|
printerModelData := glpi.GlpiItemModel{
|
||||||
|
Name: "Sys 1200",
|
||||||
|
}
|
||||||
|
printerModelID = glpiSession.ItemOperation("add", "PrinterModel", printerModelData)
|
||||||
|
}
|
||||||
|
````
|
||||||
|
|
||||||
|
|
||||||
|
Аналогичным образом поступаем и с остальными данными. Добавляем принтер с данными указанными в нижеприведенной структуре. В значениях полей указаны идентификаторы уже созданных записей, плюс переменные полученные выше (в принципе, для добавления принтера достаточно одного имени, остальное можно добавить позже):
|
||||||
|
|
||||||
|
``` go
|
||||||
|
printerData := glpi.GlpiPrinter{
|
||||||
|
Name: printerName,
|
||||||
|
Locations_id: 1,
|
||||||
|
Users_id_tech: 3,
|
||||||
|
Users_id: 2,
|
||||||
|
Groups_id_tech: 1,
|
||||||
|
Groups_id: 2,
|
||||||
|
Have_usb: 1,
|
||||||
|
Networks_id: networksID,
|
||||||
|
Manufacturers_id: manufacturersID,
|
||||||
|
Printermodels_id: printerModelID,
|
||||||
|
}
|
||||||
|
|
||||||
|
printerID := glpiSession.ItemOperation("add", "Printer", printerData)
|
||||||
|
fmt.Println("Printer was added, ID:", printerID)
|
||||||
|
```
|
||||||
|
|
||||||
|
Так как принтер подразумевается сетевой то добавим к нему сетевой порт и привяжем к нему IP-адрес. Данная функциональность подобным образом обрабатывается и для других активов GLPI, т.е. алгоритм работы тот-же меняются только itemtype.
|
||||||
|
|
||||||
|
Добавляем порт:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// Added Ethernet network port
|
||||||
|
networkPortData := glpi.GlpiNetworkPort{
|
||||||
|
Name: "Eth1",
|
||||||
|
Items_id: printerID,
|
||||||
|
Itemtype: itemType,
|
||||||
|
Logical_number: 1,
|
||||||
|
Instantiation_type: "NetworkPortEthernet",
|
||||||
|
}
|
||||||
|
glpiPortID := glpiSession.ItemOperation("add", "NetworkPort", networkPortData)
|
||||||
|
fmt.Println("Network port was added, ID: ", glpiPortID)
|
||||||
|
````
|
||||||
|
|
||||||
|
Добавляем домен:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// Getting domain ID, or add it
|
||||||
|
glpiFqdnID := glpiSession.SearchItem("FQDN", printerDomain)
|
||||||
|
if glpiFqdnID == 0 {
|
||||||
|
fqdnData := glpi.GlpiFQDN{
|
||||||
|
Name: printerDomain,
|
||||||
|
FQDN: printerDomain,
|
||||||
|
Comment: "Our local domain",
|
||||||
|
}
|
||||||
|
glpiFqdnID = glpiSession.ItemOperation("add", "fqdn", fqdnData)
|
||||||
|
}
|
||||||
|
fmt.Println("Domain - ", printerDomain, glpiFqdnID)
|
||||||
|
```
|
||||||
|
|
||||||
|
Связываем воедино сетевой порт, сетевое имя принтера и домен:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
networkData := glpi.GlpiNetworkName{
|
||||||
|
Name: printerName,
|
||||||
|
Itemtype: "NetworkPort",
|
||||||
|
Items_id: glpiPortID,
|
||||||
|
Fqdns_id: glpiFqdnID,
|
||||||
|
Comment: "Network port",
|
||||||
|
}
|
||||||
|
glpiNetworkID := glpiSession.ItemOperation("add", "NetworkName", networkData)
|
||||||
|
fmt.Println("Added network name for", printerName, "with ID:", glpiNetworkID)
|
||||||
|
```
|
||||||
|
|
||||||
|
Добавляем IP-адрес и привязываем его к принтеру и сетевому имени (порту):
|
||||||
|
|
||||||
|
``` go
|
||||||
|
ipData := glpi.GlpiIPAddress{
|
||||||
|
Name: "172.30.30.123",
|
||||||
|
Itemtype: "NetworkName",
|
||||||
|
Items_id: glpiNetworkID,
|
||||||
|
Mainitems_id: printerID,
|
||||||
|
Mainitemtype: itemType,
|
||||||
|
Comment: "Network port",
|
||||||
|
}
|
||||||
|
glpiIpAddressID := glpiSession.ItemOperation("add", "IPAddress", ipData)
|
||||||
|
fmt.Println("Added IP address:", glpiIpAddressID)
|
||||||
|
```
|
||||||
|
|
||||||
|
Т.е. схема добавления "Железка" -> "Порт" -> "Сетевое имя (сеть)" -> "IP-адрес" будет общая для всех активов или устройств имеющих сетевые порты.
|
||||||
|
|
||||||
|
На этом с принтером всё. Теперь можно добавить картриджей. Сперва добавляем модель картриджа
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// ADD cartridge
|
||||||
|
requestDataCartridgeItem := glpi.GlpiCartridgeItem{
|
||||||
|
// Id: "11",
|
||||||
|
Name: "С4092B",
|
||||||
|
// Users_id_tech: 3,
|
||||||
|
// Users_id: 2,
|
||||||
|
// Groups_id_tech: 1,
|
||||||
|
// Groups_id: 2,
|
||||||
|
// Cartridgeitemtypes_id: 0,
|
||||||
|
Manufacturers_id: manufacturersID,
|
||||||
|
Alarm_threshold: 5,
|
||||||
|
}
|
||||||
|
cartridgeItemsID := glpiSession.ItemOperation("add", "CartridgeItem", requestDataCartridgeItem)
|
||||||
|
fmt.Println("Add a cartridge item:", cartridgeItemsID)
|
||||||
|
```
|
||||||
|
|
||||||
|
Затем указываем соответсвие (добавляем запись) между моделью принтера и моделью картриджа
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// Linked printer model and cartridge
|
||||||
|
// printerModelID := glpiSession.SearchItem("PrinterModel", "Sys 1200")
|
||||||
|
requestData := glpi.GlpiCartridgeItemPrinterModel{
|
||||||
|
// Id: "11",
|
||||||
|
Cartridgeitems_id: cartridgeItemsID,
|
||||||
|
Printermodels_id: printerModelID,
|
||||||
|
}
|
||||||
|
|
||||||
|
cartridgeItemsPrinterModel := glpiSession.ItemOperation("add", "cartridgeitem_printermodel", requestData)
|
||||||
|
fmt.Println("Added a link between Cartridge model and Printer model:", cartridgeItemsPrinterModel)
|
||||||
|
```
|
||||||
|
|
||||||
|
Затем добавляем картридж уже как еденицу хранения, привязывая к модели:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// Get the ID of an existing printer, or add it
|
||||||
|
// printerID = glpiSession.SearchItem("Printer", "acc-prn1")
|
||||||
|
|
||||||
|
requestDataCartridge := glpi.GlpiCartridge{
|
||||||
|
// Id: "11",
|
||||||
|
Cartridgeitems_id: cartridgeItemsID,
|
||||||
|
}
|
||||||
|
|
||||||
|
cartridgeID := glpiSession.ItemOperation("add", "Cartridge", requestDataCartridge)
|
||||||
|
fmt.Println("Added a cartridge:", cartridgeID)
|
||||||
|
```
|
||||||
|
|
||||||
|
"Установим" картридж в принтер, т.е. привяжем конкретный картридж к конкретному принтеру:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// Getting a new cartridge info
|
||||||
|
res := glpiSession.GetItem("Cartridge", cartridgeID, "")
|
||||||
|
fmt.Println("Cartridge:", string(res))
|
||||||
|
|
||||||
|
var cartridgeInfo glpi.GlpiCartridge
|
||||||
|
err = json.Unmarshal(res, &cartridgeInfo)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Installing the cartridge in the printer
|
||||||
|
cartridgeInfo.Printers_id = printerID
|
||||||
|
cartridgeInfo.Date_use = "2021-08-20"
|
||||||
|
|
||||||
|
res1 := glpiSession.ItemOperation("update", "Cartridge", cartridgeInfo)
|
||||||
|
fmt.Println("Add a link between cartridge and printer:", res1)
|
||||||
|
```
|
||||||
|
|
||||||
|
Перед обновлением конкретной записи требуется выбрать все данные и сохранить в переменную соответствующего типа, если этого не сделать то при выполнении операции "update" не инициализированные поля будут пустыми (т.е. данные затрутся).
|
||||||
|
|
||||||
|
Для получения информации о конкретном оборудовании в модуле есть функция ```GetItem(itemType string, itemID int, otherParam string)```. Она принимает на вход тип оборудования и его ID, возвращает JSON ввиде массива байт ([]byte). Так как функция GetItem() возвращает JSON, то его можно увидеть просто преобразовав байты в строку при помощи string()
|
||||||
|
|
||||||
|
Получим информацию о добавленном картридже и выведем в косоль:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// Getting a new cartridge info
|
||||||
|
res := glpiSession.GetItem("Cartridge", cartridgeID, "")
|
||||||
|
fmt.Println("Cartridge:", string(res))
|
||||||
|
```
|
||||||
|
|
||||||
|
Для преобразования данных из json в структуру требуемого нам типа применим функцию json.Unmarshal():
|
||||||
|
|
||||||
|
``` go
|
||||||
|
var cartridgeInfo glpi.GlpiCartridge
|
||||||
|
err = json.Unmarshal(res, &cartridgeInfo)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
fmt.Println("Cartridge:", cartridgeInfo)
|
||||||
|
```
|
||||||
|
|
||||||
|
Доступ к полям структуры можно получить штатным образом:
|
||||||
|
|
||||||
|
- cartridgeInfo.Id - уникальный идентификатор
|
||||||
|
- cartridgeInfo.Printers_id - идентификатор принтера
|
||||||
|
- cartridgeInfo.Date_in - дата установкии
|
||||||
|
- и т.д.
|
||||||
|
|
||||||
|
После выполнения всех операция удаляем нашу сессию. GLPI периодически сессии очищает сам, но лучше удалить:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
_, err = glpiSession.KillSession()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
```
|
195
glpi/README.md
Normal file
195
glpi/README.md
Normal file
|
@ -0,0 +1,195 @@
|
||||||
|
GLPI
|
||||||
|
====
|
||||||
|
|
||||||
|
This Go library implements the GLPI HTTP REST API. This module provides working with all the assets and some GLPI items.
|
||||||
|
|
||||||
|
Getting started
|
||||||
|
===============
|
||||||
|
|
||||||
|
## Setting the variables
|
||||||
|
|
||||||
|
Setting a three variables for connecting a GLPI API:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
var (
|
||||||
|
glpiServerAPI string
|
||||||
|
glpiUserToken string
|
||||||
|
glpiAppToken string
|
||||||
|
)
|
||||||
|
glpiServerAPI = os.Getenv("GLPI_SERVER_API")
|
||||||
|
glpiUserToken = os.Getenv("GLPI_USER_TOKEN")
|
||||||
|
glpiAppToken = os.Getenv("GLPI_APP_TOKEN")
|
||||||
|
```
|
||||||
|
|
||||||
|
Where:
|
||||||
|
|
||||||
|
- GLPI_USER_TOKEN - the API access token for each user (setting in a user profile)
|
||||||
|
- GLPI_APP_TOKEN - the application token (setting in the "Setup"->"General"->"API" section GLPI UI)
|
||||||
|
- GLPI_SERVER_API - API URL (like as https://glpi/apirest.php)
|
||||||
|
|
||||||
|
## Connection to the API and initial session
|
||||||
|
|
||||||
|
``` go
|
||||||
|
glpiSession, err := glpi.NewSession(glpiServerAPI, glpiUserToken, glpiAppToken)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, err = glpiSession.InitSession()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
```
|
||||||
|
glpiSession.InitSession() - initializes the session, i.e. when this function is called, the module is connected to the GLPI and the session access code (token) is returned. Its value is stored in the field of the "glpi Session.session Token" structure. This code can be viewed by calling the function "glpi Session.Get Session Token ()", i.e.
|
||||||
|
|
||||||
|
``` go
|
||||||
|
fmt.Println(glpiSession.GetSessionToken())
|
||||||
|
```
|
||||||
|
|
||||||
|
Work with some items
|
||||||
|
====================
|
||||||
|
|
||||||
|
## Adding the Manufacturer
|
||||||
|
|
||||||
|
``` go
|
||||||
|
manufacturersData := glpi.GlpiManufacturer{
|
||||||
|
Name: "Yet Another",
|
||||||
|
Comment: "Yet Another inc.",
|
||||||
|
}
|
||||||
|
manufacturersID = glpiSession.ItemOperation("add", "Manufacturer", manufacturersData)
|
||||||
|
```
|
||||||
|
|
||||||
|
If it's all right, the new manufacturers ID will be written to the "manufacturersID" variable.
|
||||||
|
|
||||||
|
## Adding the printers model
|
||||||
|
|
||||||
|
For simple model types, you should use the structure GlpiItemModel and ItemModel() function:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
type GlpiSimpleItem struct {
|
||||||
|
Id int `json:"id"`
|
||||||
|
Comment string `json:"comment"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Adding the new printer model:
|
||||||
|
|
||||||
|
``` go
|
||||||
|
printerModelData := glpi.GlpiItemModel{
|
||||||
|
Name: "Sys 1200",
|
||||||
|
}
|
||||||
|
printerModelID = glpiSession.ItemOperation("add", "PrinterModel", printerModelData)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Adding the printer
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// Add new printer
|
||||||
|
printerData := glpi.GlpiPrinter{
|
||||||
|
// Id: "11",
|
||||||
|
Name: "First printer",
|
||||||
|
Have_usb: 1,
|
||||||
|
Manufacturers_id: manufacturersID,
|
||||||
|
Printermodels_id: printerModelID,
|
||||||
|
}
|
||||||
|
|
||||||
|
printerID := glpiSession.ItemOperation("add", "Printer", printerData)
|
||||||
|
fmt.Println("Printer was added, ID:", printerID)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Adding a cartridge model and linking them to the printer model
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// ADD cartridge
|
||||||
|
requestDataCartridgeItem := glpi.GlpiCartridgeItem{
|
||||||
|
// Id: "11",
|
||||||
|
Name: "С4092B",
|
||||||
|
Manufacturers_id: manufacturersID,
|
||||||
|
Alarm_threshold: 5,
|
||||||
|
}
|
||||||
|
cartridgeItemsID := glpiSession.ItemOperation("add", "CartridgeItem", requestDataCartridgeItem)
|
||||||
|
fmt.Println("Add a cartridge item:", cartridgeItemsID)
|
||||||
|
|
||||||
|
// Linked printer model and cartridge
|
||||||
|
// printerModelID := glpiSession.SearchItem("PrinterModel", "Sys 1200")
|
||||||
|
requestData := glpi.GlpiCartridgeItemPrinterModel{
|
||||||
|
// Id: "11",
|
||||||
|
Cartridgeitems_id: cartridgeItemsID,
|
||||||
|
Printermodels_id: printerModelID,
|
||||||
|
}
|
||||||
|
|
||||||
|
cartridgeItemsPrinterModel := glpiSession.ItemOperation("add", "cartridgeitem_printermodel", requestData)
|
||||||
|
fmt.Println("Added a link between Cartridge model and Printer model:", cartridgeItemsPrinterModel)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Adding a cartridge and linking them to the printer
|
||||||
|
|
||||||
|
``` go
|
||||||
|
requestDataCartridge := glpi.GlpiCartridge{
|
||||||
|
// Id: "11",
|
||||||
|
Cartridgeitems_id: cartridgeItemsID,
|
||||||
|
}
|
||||||
|
|
||||||
|
cartridgeID := glpiSession.ItemOperation("add", "Cartridge", requestDataCartridge)
|
||||||
|
fmt.Println("Added a cartridge:", cartridgeID)
|
||||||
|
|
||||||
|
// Getting a new cartridge info
|
||||||
|
res := glpiSession.GetItem("Cartridge", cartridgeID, "")
|
||||||
|
fmt.Println("Cartridge:", string(res))
|
||||||
|
|
||||||
|
var cartridgeInfo glpi.GlpiCartridge
|
||||||
|
err = json.Unmarshal(res, &cartridgeInfo)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Installing the cartridge in the printer
|
||||||
|
cartridgeInfo.Printers_id = printerID
|
||||||
|
cartridgeInfo.Date_use = "2021-08-20"
|
||||||
|
|
||||||
|
res1 := glpiSession.ItemOperation("update", "Cartridge", cartridgeInfo)
|
||||||
|
fmt.Println("Add a link between cartridge and printer:", res1)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Search the items
|
||||||
|
|
||||||
|
To get the element ID, the module provides the ```SearchItem()``` function:
|
||||||
|
|
||||||
|
``` func (glpi *Session) SearchItem(itemType string, itemName string) int {}```
|
||||||
|
|
||||||
|
If an element with the specified name was found, the function returns its ID.
|
||||||
|
|
||||||
|
``` go
|
||||||
|
// Get network ID or append new records/
|
||||||
|
networksID := glpiSession.SearchItem("Network", "Head office")
|
||||||
|
if networksID == 0 {
|
||||||
|
networksData := glpi.GlpiSimpleItem{
|
||||||
|
Name: "Head office",
|
||||||
|
Comment: "Head office network",
|
||||||
|
}
|
||||||
|
networksID = glpiSession.ItemOperation("add", "Network", networksData)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Getting ended
|
||||||
|
=============
|
||||||
|
|
||||||
|
## Kill the session
|
||||||
|
|
||||||
|
After all operations are completed, the session should be closed
|
||||||
|
|
||||||
|
``` go
|
||||||
|
_, err = glpiSession.KillSession()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
License
|
||||||
|
=======
|
||||||
|
|
||||||
|
Released under the GNU GPL License
|
1034
glpi/glpi.go
Normal file
1034
glpi/glpi.go
Normal file
File diff suppressed because it is too large
Load Diff
3
glpi/go.mod
Normal file
3
glpi/go.mod
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
module glpi
|
||||||
|
|
||||||
|
go 1.16
|
12
zabbix2glpi/go.mod
Normal file
12
zabbix2glpi/go.mod
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
module zabbix2glpi
|
||||||
|
|
||||||
|
go 1.16
|
||||||
|
|
||||||
|
replace glpi => ../glpi
|
||||||
|
|
||||||
|
replace zabbix => ../../zabbix/zabbix
|
||||||
|
|
||||||
|
require (
|
||||||
|
glpi v0.0.0-00010101000000-000000000000
|
||||||
|
zabbix v0.0.0-00010101000000-000000000000
|
||||||
|
)
|
487
zabbix2glpi/zabbix2glpi.go
Normal file
487
zabbix2glpi/zabbix2glpi.go
Normal file
|
@ -0,0 +1,487 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"glpi"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"zabbix"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Find and return a single host object by name
|
||||||
|
func GetHost(zabbixAPI *zabbix.API, host string) (zabbix.ZabbixHost, error) {
|
||||||
|
params := make(map[string]interface{}, 0)
|
||||||
|
filter := make(map[string]string, 0)
|
||||||
|
filter["host"] = host
|
||||||
|
params["filter"] = filter
|
||||||
|
params["output"] = "extend"
|
||||||
|
params["select_groups"] = "extend"
|
||||||
|
params["templated_hosts"] = 1
|
||||||
|
params["selectInventory"] = "extend"
|
||||||
|
params["selectInterfaces"] = "extend"
|
||||||
|
ret, err := zabbixAPI.Host("get", params)
|
||||||
|
|
||||||
|
// This happens if there was an RPC error
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// If our call was successful
|
||||||
|
if len(ret) > 0 {
|
||||||
|
return ret[0], err
|
||||||
|
}
|
||||||
|
|
||||||
|
// This will be the case if the RPC call was successful, but
|
||||||
|
// Zabbix had an issue with the data we passed.
|
||||||
|
return nil, &zabbix.ZabbixError{0, "", "Host not found"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetHostGroup(zabbixAPI *zabbix.API, hostgroup string, select_type string) (zabbix.ZabbixHostGroup, error) {
|
||||||
|
params := make(map[string]interface{}, 0)
|
||||||
|
filter := make(map[string]string, 0)
|
||||||
|
filter["name"] = hostgroup
|
||||||
|
params["filter"] = filter
|
||||||
|
params["output"] = "extend"
|
||||||
|
if select_type == "all_hosts" {
|
||||||
|
params["selectHosts"] = "extend"
|
||||||
|
}
|
||||||
|
// params["select_groups"] = "extend"
|
||||||
|
//params["templated_hosts"] = 1
|
||||||
|
ret, err := zabbixAPI.HostGroup("get", params)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// If our call was successful
|
||||||
|
if len(ret) > 0 {
|
||||||
|
return ret[0], err
|
||||||
|
}
|
||||||
|
|
||||||
|
// This will be the case if the RPC call was successful, but
|
||||||
|
// Zabbix had an issue with the data we passed.
|
||||||
|
return nil, &zabbix.ZabbixError{0, "", "HostGroup not found"}
|
||||||
|
}
|
||||||
|
|
||||||
|
func MigrateHost(glpiAPI *glpi.Session, zabbixAPI *zabbix.API, item interface{}, glpiLocationID int) {
|
||||||
|
var (
|
||||||
|
zbxHostOS string
|
||||||
|
zbxHostIP string
|
||||||
|
zbxHostFQDN string
|
||||||
|
zbxHostSerial string
|
||||||
|
zbxHostOtherSerial string
|
||||||
|
zbxHostUseDate string
|
||||||
|
zbxHostManufacturer string
|
||||||
|
zbxHostComputerModel string
|
||||||
|
glpiItemStatusID int
|
||||||
|
)
|
||||||
|
itemType := "Computer"
|
||||||
|
typeID := glpiAPI.SearchItem("ComputerType", "Сервер")
|
||||||
|
// location_id := glpiAPI.SearchItem("Location", "ГО")
|
||||||
|
fmt.Println(typeID)
|
||||||
|
// Получаем имя узла, id и флаг инвентаризации
|
||||||
|
zbxHostName := fmt.Sprint(item.(map[string]interface{})["host"])
|
||||||
|
|
||||||
|
zbxHostStatus := fmt.Sprint(item.(map[string]interface{})["status"])
|
||||||
|
// // если "inventory_mode": "-1" то инвентаризация отключена
|
||||||
|
zbxHostHasInventory := fmt.Sprint(item.(map[string]interface{})["inventory_mode"])
|
||||||
|
// Если имя узла в заббикс как FQDN то обрезаем до первой точки
|
||||||
|
// zbxHostName_short := strings.Split(zbxHostName, ".")[0]
|
||||||
|
|
||||||
|
glpiCompID := glpiAPI.SearchItem("Computer", strings.ToLower(zbxHostName))
|
||||||
|
|
||||||
|
fmt.Println(">>>>>>> ", zbxHostName)
|
||||||
|
|
||||||
|
if glpiCompID != 0 {
|
||||||
|
fmt.Println("Узел ", zbxHostName, " существует в glpi c id:", glpiCompID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// По имени узла запрашиваем полную информацию из заббикса и выдергиваем данные
|
||||||
|
zbxHostInfo, _ := GetHost(zabbixAPI, fmt.Sprint(zbxHostName))
|
||||||
|
for _, i := range zbxHostInfo["interfaces"].([]interface{}) {
|
||||||
|
zbxHostIP = fmt.Sprint(i.(map[string]interface{})["ip"])
|
||||||
|
zbxHostFQDN = strings.ToLower(fmt.Sprint(i.(map[string]interface{})["dns"]))
|
||||||
|
fmt.Println(zbxHostIP, zbxHostFQDN)
|
||||||
|
}
|
||||||
|
// Проверяем если флаг инвентаризации не равен -1 то получаем инвентарные данные
|
||||||
|
if zbxHostHasInventory != "-1" {
|
||||||
|
zbxHostOS = fmt.Sprint(zbxHostInfo["inventory"].(map[string]interface{})["os"])
|
||||||
|
zbxHostSerial = fmt.Sprint(zbxHostInfo["inventory"].(map[string]interface{})["serialno_a"])
|
||||||
|
zbxHostOtherSerial = fmt.Sprint(zbxHostInfo["inventory"].(map[string]interface{})["serialno_b"])
|
||||||
|
zbxHostUseDate = fmt.Sprint(zbxHostInfo["inventory"].(map[string]interface{})["date_hw_install"])
|
||||||
|
zbxHostManufacturer = fmt.Sprint(zbxHostInfo["inventory"].(map[string]interface{})["vendor"])
|
||||||
|
zbxHostComputerModel = fmt.Sprint(zbxHostInfo["inventory"].(map[string]interface{})["model"])
|
||||||
|
|
||||||
|
fmt.Println(zbxHostOS, zbxHostSerial, zbxHostOtherSerial, zbxHostUseDate, zbxHostManufacturer, zbxHostComputerModel)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// получаем id модели оборудования. Если не найдено добавляем в glpi
|
||||||
|
glpiModelID := glpiAPI.SearchItem("ComputerModel", zbxHostComputerModel)
|
||||||
|
if glpiModelID == 0 {
|
||||||
|
requestData := glpi.GlpiComputerModel{
|
||||||
|
Name: zbxHostComputerModel,
|
||||||
|
}
|
||||||
|
glpiModelID = glpiAPI.ItemOperation("add", "ComputerModel", requestData)
|
||||||
|
}
|
||||||
|
|
||||||
|
// получаем id производителя из glpiAPI. если нету добавляем
|
||||||
|
glpiManufacturerID := glpiAPI.SearchItem("Manufacturer", zbxHostManufacturer)
|
||||||
|
if glpiManufacturerID == 0 {
|
||||||
|
requestData := glpi.GlpiManufacturer{
|
||||||
|
Name: zbxHostManufacturer,
|
||||||
|
}
|
||||||
|
glpiManufacturerID = glpiAPI.ItemOperation("add", "Manufacturer", requestData)
|
||||||
|
}
|
||||||
|
|
||||||
|
// добавляем железку
|
||||||
|
// проверяем статус
|
||||||
|
if zbxHostStatus == "0" {
|
||||||
|
glpiItemStatusID = glpiAPI.SearchItem("State", "В работе")
|
||||||
|
}
|
||||||
|
if zbxHostStatus == "1" {
|
||||||
|
glpiItemStatusID = glpiAPI.SearchItem("State", "Выключено")
|
||||||
|
}
|
||||||
|
|
||||||
|
requestDataComp := glpi.GlpiComputer{
|
||||||
|
Name: strings.ToLower(zbxHostName),
|
||||||
|
Serial: zbxHostSerial,
|
||||||
|
Otherserial: zbxHostOtherSerial,
|
||||||
|
Locations_id: glpiLocationID,
|
||||||
|
Computermodels_id: glpiModelID,
|
||||||
|
Computertypes_id: typeID,
|
||||||
|
Manufacturers_id: glpiManufacturerID,
|
||||||
|
States_id: glpiItemStatusID,
|
||||||
|
}
|
||||||
|
glpiCompID = glpiAPI.ItemOperation("add", "Computer", requestDataComp)
|
||||||
|
fmt.Println("Добавлен хост", glpiCompID)
|
||||||
|
|
||||||
|
// Если выставлена дата установки то включаем фин. информаци.
|
||||||
|
// к году прибвавляем месяц и день
|
||||||
|
if len(zbxHostUseDate) <= 4 {
|
||||||
|
zbxHostUseDate = zbxHostUseDate + "-01-01"
|
||||||
|
}
|
||||||
|
if zbxHostUseDate != "" {
|
||||||
|
requestDataInfocom := glpi.GlpiInfocom{
|
||||||
|
Items_id: glpiCompID,
|
||||||
|
Itemtype: itemType,
|
||||||
|
Use_date: zbxHostUseDate,
|
||||||
|
}
|
||||||
|
// fmt.Println("--->", requestDataInfocom)
|
||||||
|
glpiAPI.ItemOperation("add", "InfoCom", requestDataInfocom)
|
||||||
|
fmt.Println("Добавлена фин. информация ", glpiCompID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Добавляем сетевой порт, адрес, FQDN, e.t.c
|
||||||
|
if zbxHostIP != "" {
|
||||||
|
glpiNetworkPortData := glpi.GlpiNetworkPort{
|
||||||
|
Items_id: glpiCompID,
|
||||||
|
Itemtype: itemType,
|
||||||
|
Name: "Eth",
|
||||||
|
Instantiation_type: "NetworkPortEthernet",
|
||||||
|
}
|
||||||
|
glpiPortID := glpiAPI.ItemOperation("add", "NetworkPort", glpiNetworkPortData)
|
||||||
|
fmt.Println("Добавлен port", glpiPortID)
|
||||||
|
|
||||||
|
// Отделяем имя узла от домена
|
||||||
|
zbxHostFQDN_short := strings.Split(zbxHostFQDN, ".")[0]
|
||||||
|
prefix := zbxHostFQDN_short + "."
|
||||||
|
zbxHostDomain := strings.TrimLeft(zbxHostFQDN, prefix)
|
||||||
|
fmt.Println(zbxHostFQDN, zbxHostFQDN_short, zbxHostDomain)
|
||||||
|
// Определяем ID домена в GLPI если он там есть
|
||||||
|
glpiFqdnID := glpiAPI.SearchItem("FQDN", zbxHostDomain)
|
||||||
|
fmt.Println("Домен - ", zbxHostDomain, glpiFqdnID)
|
||||||
|
|
||||||
|
glpiNetworkData := glpi.GlpiNetworkName{
|
||||||
|
Items_id: glpiPortID,
|
||||||
|
Itemtype: "NetworkPort",
|
||||||
|
Name: zbxHostFQDN_short,
|
||||||
|
Fqdns_id: glpiFqdnID,
|
||||||
|
}
|
||||||
|
glpiNetworkID := glpiAPI.ItemOperation("add", "NetworkName", glpiNetworkData)
|
||||||
|
fmt.Println("Добавлена сеть", glpiNetworkID)
|
||||||
|
|
||||||
|
glpiIPAdressData := glpi.GlpiIPAddress{
|
||||||
|
Items_id: glpiNetworkID,
|
||||||
|
Itemtype: "NetworkName",
|
||||||
|
Name: zbxHostIP,
|
||||||
|
}
|
||||||
|
glpiIpAddressID := glpiAPI.ItemOperation("add", "IPAddress", glpiIPAdressData)
|
||||||
|
fmt.Println("Добавлен IP", glpiIpAddressID)
|
||||||
|
}
|
||||||
|
// Проверяем что в заббикс для узла есть запись об ОС
|
||||||
|
if zbxHostOS != "" {
|
||||||
|
// получаем id ОС из glpiAPI. если нет добавляем
|
||||||
|
glpiOSID := glpiAPI.SearchItem("OperatingSystem", zbxHostOS)
|
||||||
|
fmt.Println("Добавлена ОС", glpiOSID)
|
||||||
|
if glpiOSID == 0 {
|
||||||
|
// request_data_os := glpi.GlpiOperatingSystem{
|
||||||
|
// Name: zbxHostOS,
|
||||||
|
// }
|
||||||
|
glpiOSID = glpiAPI.ItemOperation("add", "OperatingSystem", glpi.GlpiOperatingSystem{Name: zbxHostOS})
|
||||||
|
fmt.Println("Добавлена ОС", glpiOSID)
|
||||||
|
}
|
||||||
|
// Привязываем ОС к узлу в GLPI
|
||||||
|
requestDataOSItem := glpi.GlpiOSItem{
|
||||||
|
Items_id: glpiCompID,
|
||||||
|
Itemtype: itemType,
|
||||||
|
Operatingsystems_id: glpiOSID,
|
||||||
|
}
|
||||||
|
glpiAPI.ItemOperation("add", "Item_OperatingSystem", requestDataOSItem)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateHostStatus(glpiAPI *glpi.Session, zabbixAPI *zabbix.API, item interface{}) {
|
||||||
|
// Получаем имя узла, id и флаг инвентаризации
|
||||||
|
itemType := "Computer"
|
||||||
|
// typeID := glpiAPI.SearchItem("ComputerType", "Сервер")
|
||||||
|
|
||||||
|
zbxHostName := fmt.Sprint(item.(map[string]interface{})["host"])
|
||||||
|
|
||||||
|
zbxHostStatus := fmt.Sprint(item.(map[string]interface{})["status"])
|
||||||
|
glpiItemID := glpiAPI.SearchItem(itemType, strings.ToLower(zbxHostName))
|
||||||
|
res := glpiAPI.GetItem(itemType, glpiItemID, "")
|
||||||
|
|
||||||
|
var statusInfo map[string]interface{}
|
||||||
|
err := json.Unmarshal(res, &statusInfo)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
glpiItemStatusID := statusInfo["states_id"]
|
||||||
|
|
||||||
|
fmt.Println(">>>>>>> ", zbxHostName, zbxHostStatus, "glp id:", glpiItemID, "glpi status", glpiItemStatusID)
|
||||||
|
|
||||||
|
var glpiStatusID int
|
||||||
|
|
||||||
|
if zbxHostStatus == "0" {
|
||||||
|
glpiStatusID = glpiAPI.SearchItem("State", "В работе")
|
||||||
|
}
|
||||||
|
if zbxHostStatus == "1" {
|
||||||
|
glpiStatusID = glpiAPI.SearchItem("State", "Выключено")
|
||||||
|
}
|
||||||
|
fmt.Println(glpiItemStatusID, glpiStatusID)
|
||||||
|
if glpiItemStatusID != glpiStatusID {
|
||||||
|
fmt.Println("Update")
|
||||||
|
glpiAPI.UpdateItemStatus(itemType, glpiItemID, glpiStatusID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var (
|
||||||
|
zabbixServerAPI string
|
||||||
|
zabbixUser string
|
||||||
|
zabbixPassword string
|
||||||
|
zabbixHost string
|
||||||
|
zabbixHostGroups string
|
||||||
|
operation string
|
||||||
|
outputFormat string
|
||||||
|
glpiServerAPI string
|
||||||
|
glpiUserToken string
|
||||||
|
glpiAppToken string
|
||||||
|
glpiLocationID int
|
||||||
|
)
|
||||||
|
|
||||||
|
flag.StringVar(&zabbixServerAPI, "zabbix-server-api", "", "zabbix server API URL. ZABBIX_SERVER_API")
|
||||||
|
flag.StringVar(&zabbixUser, "zabbix-user", "", "Zabbix user name. ZABBIX_USER")
|
||||||
|
flag.StringVar(&zabbixPassword, "zabbix-password", "", "Zabbix password. ZABBIX_PASSWORD")
|
||||||
|
flag.StringVar(&zabbixHost, "zabbix-host", "", "Zabbix host name")
|
||||||
|
flag.StringVar(&zabbixHostGroups, "zabbix-host-groups", "", "Zabbix host groups, can be comma-separated list")
|
||||||
|
|
||||||
|
flag.StringVar(&glpiServerAPI, "glpi-server-api", "", "Glpi instance API URL. GLPI_SERVER_URL")
|
||||||
|
flag.StringVar(&glpiUserToken, "glpi-user-token", "", "Glpi user API token. GLPI_USER_TOKEN")
|
||||||
|
flag.StringVar(&glpiAppToken, "glpi-app-token", "", "Glpi aplication API token. GLPI_APP_TOKEN")
|
||||||
|
flag.IntVar(&glpiLocationID, "glpi-location-id", 0, "Glpi location id for migration hosts")
|
||||||
|
|
||||||
|
flag.StringVar(&operation, "operation", "zabbix-version", "Opertation type, must be:\n\tzabbix-version\n\tglpi-version\n\tget-host - getting zabbix host information\n\tget-hostgroup - getting zabbix hosts group\n\tget-hosts-from-group - getting zabbix group members hosts\n\tmigrate-host - migrate host from Zabbix to GLPI\n\tmigrate-hosts-from-group - migrate all zabbix groups members hosts to GLPI\n\tupdate-host-status - get host status from zabbix and update them into zabbix\n\tupdate-hosts-status-from-group - get group members hosts status from zabbix and update into glpi\n\t")
|
||||||
|
|
||||||
|
flag.StringVar(&outputFormat, "output-format", "go", "Output format: 'go' - go map, 'json' - json string")
|
||||||
|
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
if zabbixServerAPI == "" && os.Getenv("ZABBIX_SERVER_API") == "" {
|
||||||
|
fmt.Println("Send error: make sure environment variables `ZABBIX_SERVER_API`, or used with '-zabbix-server-api' argument")
|
||||||
|
os.Exit(1)
|
||||||
|
} else if zabbixServerAPI == "" && os.Getenv("ZABBIX_SERVER_API") != "" {
|
||||||
|
zabbixServerAPI = os.Getenv("ZABBIX_SERVER_API")
|
||||||
|
}
|
||||||
|
// fmt.Println(zabbixServerAPI)
|
||||||
|
|
||||||
|
if zabbixUser == "" && os.Getenv("ZABBIX_USER") == "" {
|
||||||
|
fmt.Println("Send error: make sure environment variables `ZABBIX_USER`, or used with '-zabbix-user' argument")
|
||||||
|
os.Exit(1)
|
||||||
|
} else if zabbixUser == "" && os.Getenv("ZABBIX_USER") != "" {
|
||||||
|
zabbixUser = os.Getenv("ZABBIX_USER")
|
||||||
|
}
|
||||||
|
// fmt.Println(zabbixUser )
|
||||||
|
|
||||||
|
if zabbixPassword == "" && os.Getenv("ZABBIX_PASSWORD") == "" {
|
||||||
|
fmt.Println("Send error: make sure environment variables `ZABBIX_PASSWORD`, or used with '-zabbix-password' argument")
|
||||||
|
os.Exit(1)
|
||||||
|
} else if zabbixPassword == "" && os.Getenv("ZABBIX_PASSWORD") != "" {
|
||||||
|
zabbixPassword = os.Getenv("ZABBIX_PASSWORD")
|
||||||
|
}
|
||||||
|
// fmt.Println(zabbixPassword)
|
||||||
|
|
||||||
|
//-----------------------------------------------------------
|
||||||
|
if glpiServerAPI == "" && os.Getenv("GLPI_SERVER_API") == "" {
|
||||||
|
fmt.Println("Send error: make sure environment variables `GLPI_SERVER_API`, or used with '-glpi-server-api' argument")
|
||||||
|
os.Exit(1)
|
||||||
|
} else if glpiServerAPI == "" && os.Getenv("GLPI_SERVER_API") != "" {
|
||||||
|
glpiServerAPI = os.Getenv("GLPI_SERVER_API")
|
||||||
|
}
|
||||||
|
|
||||||
|
if glpiUserToken == "" && os.Getenv("GLPI_USER_TOKEN") == "" {
|
||||||
|
fmt.Println("Send error: make sure environment variables `GLPI_USER_TOKEN`, or used with '-glpi-user-token' argument")
|
||||||
|
os.Exit(1)
|
||||||
|
} else if glpiUserToken == "" && os.Getenv("GLPI_USER_TOKEN") != "" {
|
||||||
|
glpiUserToken = os.Getenv("GLPI_USER_TOKEN")
|
||||||
|
}
|
||||||
|
|
||||||
|
if glpiAppToken == "" && os.Getenv("GLPI_APP_TOKEN") == "" {
|
||||||
|
fmt.Println("Send error: make sure environment variables `GLPI_APP_TOKEN`, or used with '-glpi-app-token' argument")
|
||||||
|
os.Exit(1)
|
||||||
|
} else if glpiAppToken == "" && os.Getenv("GLPI_APP_TOKEN") != "" {
|
||||||
|
glpiAppToken = os.Getenv("GLPI_APP_TOKEN")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------- Connected to zabbix API ----------
|
||||||
|
zabbixAPI, err := zabbix.NewAPI(zabbixServerAPI, zabbixUser, zabbixPassword)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if operation != "zabbix-version" {
|
||||||
|
_, err = zabbixAPI.Login()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// fmt.Println("Connected to API: OK")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------- Connected to GLPI API -----------
|
||||||
|
glpiAPI, err := glpi.NewSession(glpiServerAPI, glpiUserToken, glpiAppToken)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, err = glpiAPI.InitSession()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
switch operation {
|
||||||
|
case "zabbix-version":
|
||||||
|
zabbixVersion, err := zabbixAPI.Version()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
fmt.Println("Zabbix version:", zabbixVersion)
|
||||||
|
case "glpi-version":
|
||||||
|
glpiVersion := glpiAPI.Version()
|
||||||
|
fmt.Println("GLPI version:", glpiVersion)
|
||||||
|
case "get-host":
|
||||||
|
if zabbixHost == "" {
|
||||||
|
fmt.Println("Zabbix host not setting, using '-zabbix-host' command line argument")
|
||||||
|
os.Exit(1)
|
||||||
|
} else {
|
||||||
|
res, err := GetHost(zabbixAPI, zabbixHost)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
if outputFormat == "json" {
|
||||||
|
result, err := json.Marshal(res)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
fmt.Println(string(result))
|
||||||
|
} else {
|
||||||
|
fmt.Println(res)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "get-hostgroup":
|
||||||
|
if zabbixHostGroups == "" {
|
||||||
|
fmt.Println("Zabbix host group not setting, using '-zabbix-host-groups' command line argument")
|
||||||
|
os.Exit(1)
|
||||||
|
} else {
|
||||||
|
groupList := strings.Split(zabbixHostGroups, ",")
|
||||||
|
for _, item := range groupList {
|
||||||
|
fmt.Println(GetHostGroup(zabbixAPI, strings.TrimSpace(item), "no_host"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "get-hosts-from-group":
|
||||||
|
if zabbixHostGroups == "" {
|
||||||
|
fmt.Println("Zabbix host group not setting, using '-zabbix-host-groups' command line argument and comma separated list of groups into qoute")
|
||||||
|
os.Exit(1)
|
||||||
|
} else {
|
||||||
|
groupList := strings.Split(zabbixHostGroups, ",")
|
||||||
|
for _, item := range groupList {
|
||||||
|
res, err1 := GetHostGroup(zabbixAPI, strings.TrimSpace(item), "all_hosts")
|
||||||
|
// println(strings.TrimSpace(item))
|
||||||
|
if err1 != nil {
|
||||||
|
fmt.Println(err1)
|
||||||
|
}
|
||||||
|
if outputFormat == "json" {
|
||||||
|
result, err := json.Marshal(res)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
// если "inventory_mode": "-1" то инвентаризация отключена
|
||||||
|
fmt.Println(string(result))
|
||||||
|
} else {
|
||||||
|
fmt.Println(res)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "migrate-host":
|
||||||
|
fmt.Println("Function not implemented yet")
|
||||||
|
case "migrate-hosts-from-group":
|
||||||
|
if zabbixHostGroups == "" {
|
||||||
|
fmt.Println("Zabbix host group not setting, using '-zabbix-host-groups' command line argument and comma separated list of groups into qoute")
|
||||||
|
os.Exit(1)
|
||||||
|
} else {
|
||||||
|
groupList := strings.Split(zabbixHostGroups, ",")
|
||||||
|
for _, item := range groupList {
|
||||||
|
res, err1 := GetHostGroup(zabbixAPI, strings.TrimSpace(item), "all_hosts")
|
||||||
|
println(strings.TrimSpace(item))
|
||||||
|
if err1 != nil {
|
||||||
|
fmt.Println(err1)
|
||||||
|
}
|
||||||
|
// Пробегаемся по массиву узлов из забикса и выдергиваем интерфейсы и инвентарные данные
|
||||||
|
for _, item := range res["hosts"].([]interface{}) {
|
||||||
|
MigrateHost(glpiAPI, zabbixAPI, item, glpiLocationID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "update-host-status":
|
||||||
|
fmt.Println("Function not implemented yet")
|
||||||
|
case "update-hosts-status-from-group":
|
||||||
|
if zabbixHostGroups == "" {
|
||||||
|
fmt.Println("Zabbix host group not setting, using '-zabbix-host-groups' command line argument and comma separated list of groups into qoute")
|
||||||
|
os.Exit(1)
|
||||||
|
} else {
|
||||||
|
groupList := strings.Split(zabbixHostGroups, ",")
|
||||||
|
for _, item := range groupList {
|
||||||
|
res, err1 := GetHostGroup(zabbixAPI, strings.TrimSpace(item), "all_hosts")
|
||||||
|
println(strings.TrimSpace(item))
|
||||||
|
if err1 != nil {
|
||||||
|
fmt.Println(err1)
|
||||||
|
}
|
||||||
|
// Пробегаемся по массиву узлов из забикса и выдергиваем статус
|
||||||
|
for _, item := range res["hosts"].([]interface{}) {
|
||||||
|
fmt.Println(item)
|
||||||
|
UpdateHostStatus(glpiAPI, zabbixAPI, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user