code: def write_connection_file(
      fname=None,
      shell_port=0,
      iopub_port=0,
      stdin_port=0,
      hb_port=0,
      control_port=0,
      ip="",
      key=b"",
      transport="tcp",
      signature_scheme="hmac-sha256",
      kernel_name="",
  ):
      """Generates a JSON config file, including the selection of random ports.
  
      Parameters
      ----------
  
      fname : unicode
          The path to the file to write
  
      shell_port : int, optional
          The port to use for ROUTER (shell) channel.
  
      iopub_port : int, optional
          The port to use for the SUB channel.
  
      stdin_port : int, optional
          The port to use for the ROUTER (raw input) channel.
  
      control_port : int, optional
          The port to use for the ROUTER (control) channel.
  
      hb_port : int, optional
          The port to use for the heartbeat REP channel.
  
      ip  : str, optional
          The ip address the kernel will bind to.
  
      key : str, optional
          The Session key used for message authentication.
  
      signature_scheme : str, optional
          The scheme used for message authentication.
          This has the form 'digest-hash', where 'digest'
          is the scheme used for digests, and 'hash' is the name of the hash function
          used by the digest scheme.
          Currently, 'hmac' is the only supported digest scheme,
          and 'sha256' is the default hash function.
  
      kernel_name : str, optional
          The name of the kernel currently connected to.
      """
      if not ip:
          ip = localhost()
      # default to temporary connector file
      if not fname:
          fd, fname = tempfile.mkstemp(".json")
          os.close(fd)
  
      # Find open ports as necessary.
  
      ports = []
      ports_needed = (
          int(shell_port <= 0)
          + int(iopub_port <= 0)
          + int(stdin_port <= 0)
          + int(control_port <= 0)
          + int(hb_port <= 0)
      )
      if transport == "tcp":
          for i in range(ports_needed):
              sock = socket.socket()
              # struct.pack('ii', (0,0)) is 8 null bytes
              sock.setsockopt(
                  socket.SOL_SOCKET, socket.SO_LINGER, b"\0" * 8
              )
              sock.bind((ip, 0))
              ports.append(sock)
          for i, sock in enumerate(ports):
              port = sock.getsockname()[1]
              sock.close()
              ports[i] = port
      else:
          N = 1
          for i in range(ports_needed):
              while os.path.exists("%s-%s" % (ip, str(N))):
                  N += 1
              ports.append(N)
              N += 1
      if shell_port <= 0:
          shell_port = ports.pop(0)
      if iopub_port <= 0:
          iopub_port = ports.pop(0)
      if stdin_port <= 0:
          stdin_port = ports.pop(0)
      if control_port <= 0:
          control_port = ports.pop(0)
      if hb_port <= 0:
          hb_port = ports.pop(0)
  
      cfg = dict(
          shell_port=shell_port,
          iopub_port=iopub_port,
          stdin_port=stdin_port,
          control_port=control_port,
          hb_port=hb_port,
      )
      cfg["ip"] = ip
      cfg["key"] = bytes_to_str(key)
      cfg["transport"] = transport
      cfg["signature_scheme"] = signature_scheme
      cfg["kernel_name"] = kernel_name
  
      # Only ever write this file as user read/writeable
      # This would otherwise introduce a vulnerability as a file has secrets
      # which would let others execute arbitrarily code as you
      with secure_write(fname) as f:
          f.write(json.dumps(cfg, indent=2))
  
      if hasattr(stat, "S_ISVTX"):
          # set the sticky bit on the file and its parent directory
          # to avoid periodic cleanup
          paths = [fname]
          runtime_dir = os.path.dirname(fname)
          if runtime_dir:
              paths.append(runtime_dir)
          for path in paths:
              permissions = os.stat(path).st_mode
              new_permissions = permissions | stat.S_ISVTX
              if new_permissions != permissions:
                  try:
                      os.chmod(path, new_permissions)
                  except OSError as e:
                      if e.errno == errno.EPERM and path == runtime_dir:
                          # suppress permission errors setting sticky bit on runtime_dir,
                          # which we may not own.
                          pass
                      else:
                          # failed to set sticky bit, probably not a big deal
                          warnings.warn(
                              "Failed to set sticky bit on %r: %s"
                              "\nProbably not a big deal, but runtime files may be cleaned up periodically."
                              % (path, e),
                              RuntimeWarning,
                          )
  
      return fname, cfg
  
imports: from __future__ import absolute_import
  import errno
  import glob
  import json
  import os
  import socket
  import stat
  import tempfile
  import warnings
  from getpass import getpass
  from contextlib import contextmanager
  import zmq
  from traitlets.config import LoggingConfigurable
  from .localinterfaces import localhost
  from ipython_genutils.path import filefind
  from ipython_genutils.py3compat import bytes_to_str, cast_bytes, cast_bytes_py2, string_types
  from traitlets import Bool, Integer, Unicode, CaselessStrEnum, Instance, Type
  from jupyter_core.paths import jupyter_data_dir, jupyter_runtime_dir, secure_write
label_desc: Use image node_id 1 for calling a global function with example usage: write_connection_file(fname, shell_port, iopub_port, stdin_port, hb_port, control_port, ip, key, transport, signature_scheme, kernel_name) and returns: fname,  cfg